swift - 如何像android密码一样快速加密和解密?

标签 swift api encoding decoding

我有一个 android 类,它使用 key 对我的文本进行编码和解码,但我想为 swift 创建相同的类。

“我正在设置一个新服务器,并希望在我的 Web 应用程序中完全支持 UTF-8。我需要在哪里设置编码/字符集?”

公共(public)类加密解密{ 字符串 strResult;

public  String Encrypt(String text, String key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] keyBytes = new byte[16];
    byte[] b = key.getBytes("UTF-8");
    int len = b.length;
    if (len > keyBytes.length)
        len = keyBytes.length;
    System.arraycopy(b, 0, keyBytes, 0, len);
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

    byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
    Log.v("GET Result from  final:", results.toString());
    strResult = Base64.encodeToString(results, 1);

    Log.v("Encrypt01:", strResult);
    Log.v("Encrypt02:", results.toString());
    return strResult;
}


public String Decrypt(String text, String key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //this parameters should not be changed
    byte[] keyBytes = new byte[16];
    byte[] b = key.getBytes("UTF-8");
    int len = b.length;
    if (len > keyBytes.length)
        len = keyBytes.length;
    System.arraycopy(b, 0, keyBytes, 0, len);
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] results = new byte[text.length()];
    //BASE64Decoder decoder = new BASE64Decoder();
    try {
        results = cipher.doFinal(Base64.decode(text, Base64.DEFAULT));
    } catch (Exception e) {
        Log.i("Error in Decryption", e.toString());
    }
    Log.i("Data", new String(results, "UTF-8"));
    //return new String(results, "UTF-8"); // it returns the result as a String
    return new String(results, "UTF-8");
}

最佳答案

对于 swift 4 我找到了这个答案谢谢大家

  import CommonCrypto
  extension String {

    func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = self.data(using: String.Encoding.utf8),
            let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {


            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)



            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
                return base64cryptString


            }
            else {
                return nil
            }
        }
        return nil
    }

    func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
            let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCDecrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      data.bytes, data.length,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
                return unencryptedMessage
            }
            else {
                return nil
            }
        }
        return nil
    }


}

关于swift - 如何像android密码一样快速加密和解密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55306672/

相关文章:

ios - Xcode 7 中的 SIGABRT 错误

regex - Jax-RS 重载方法/路径执行顺序

Python - 使用utf-8编码读写csv文件

ios - 从嵌入在 UIContainerView 中的 View 调用父 View 的方法。 swift

uitableview - Swift - 在自定义单元格中添加长按手势识别器

json - 是否可以将单级 JSON 解码为 2 个独立的模型?

java - Reddit Api unsupported_grant_type 错误与 Retrofit (java)

python - JSON 架构 : validate a number-or-null value

Python Web 服务器 UTF8 编码

sqlite - 在AIR应用程序中发布PRAGMA声明