我试图用128个密钥与以下代码解密消息。这是字符串的扩展:
func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
data = NSData(base64EncodedString: self, options: .IgnoreUnknownCharacters),
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.bytes, keyLength,
nil,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let unencryptedMessage = String(data: cryptData, encoding:NSUTF8StringEncoding)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}
对于输入向量(iv(,我使用零值。存在crypdata,但我无法正确阅读此内容, uncryptedMessage 也是零。在线工具通知数据是否不正确,但是在后端侧它可以正常工作。
键值和消息价值为base64url。
用法:
let decryptedMessage = message.aesDecrypt(keyTodecrypt, iv: nil)
Swift 2.3
正如Rob所说,主要问题是输入数据。因此,我将消息和键转换为十六进制。如果您遇到相同的麻烦,请确保您的价值在客户端和后端端具有相同的编码参数。对我来说是UTF-8。另外,您应该检查密钥长度。