下面是我的android java代码,实际上是如何在IOS Swift3中编写的?
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] cipherText = cipher.doFinal(plainTextBytes);
在SO上找到AES或DES通用加密示例,并根据需要对3DES进行更改。确保密钥为 24 字节。
改变:
- 算法:
CCAlgorithm3DES
- 模式:
kCCModeECB
- 选项:
ccPKCS7Padding
如果密钥为 16 字节,则为双密钥 3DES,复制前 8 个字节并将其附加到密钥末尾以创建 24 字节密钥。
注意:DESede
称为3DES或Tripple-DES。
3DES确实不安全,尤其是2键3DES。如果可能的话,用随机IV更新到AES-CBC。
这是未经测试的 Swift 3(也应该与 Swift4 一起使用(代码,请注意上面关于密钥长度的警告:
func trippleDESCrypt(data:Data, keyData:Data, ivData:Data, operation:Int) -> Data? {
let cryptLength = size_t(data.count + kCCBlockSize3DES)
var cryptData = Data(repeating:0, count:cryptLength)
var numBytesEncrypted :size_t = 0
let keyLength = keyData.count
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding | kCCModeECB)
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
data.withUnsafeBytes {dataBytes in
ivData.withUnsafeBytes {ivBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(operation),
algoritm,
options,
keyBytes, keyLength,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.count = numBytesEncrypted
}
else {
print("Error: (cryptStatus)")
return nil
}
return cryptData
}
像往常一样,您需要有一个包含导入的桥接头文件:
#import <CommonCrypto/CommonCrypto.h>
并且您需要包含框架:
Security.framework.