下面是我的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);
答案 0 :(得分:0)
在SO上找到AES或DES Common Crypto示例,并根据需要对3DES进行更改。确保密钥是24字节。
变化:
CCAlgorithm3DES
kCCModeECB
ccPKCS7Padding
如果密钥是16字节,则它是双键3DES,复制并将前8个字节附加到密钥的末尾以创建24字节密钥。
注意:DESede
称为3DES或Tripple-DES。
3DES真的不安全,尤其是双键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.