我试图在swift3中加密一个字符串,我的加密每次都会给出不同的输出。为什么?(我在python中尝试过类似的加密,加密后的输出总是相同的)。在
下面是我的Swift 3 aesEncrypt函数:
func aesEncrypt(key:String, iv:Array<Any>, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = sha256(string:key),
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 algorithm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algorithm,
options,
(keyData as NSData).bytes, keyLength,
iv,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
// ADDED PRINT STATEMENTS
print("keyData")
print(keyData)
print("\(keyData as NSData)")
print("iv")
print(iv)
var hex_iv = toHexString(arr: iv as! [UInt8])
print(hex_iv)
print("data")
print(data)
print("\(data as NSData)")
print("encryption: cryptdata")
print(cryptData)
print("encryption: num bytes encrypted")
print(numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
}
else {
return nil
}
}
return nil
}
当我尝试使用initial_string=“hello”运行以下代码时,每次都会得到不同的加密输出字符串。在
^{pr2}$第一次运行带有“hello”字符串的代码的示例输出:
keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<b17d67fc 26e3f316 6a2bdfbf 9d387c2d 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("sX1n/Cbj8xZqK9+/nTh8LQ==")
第二次运行带有“hello”字符串的代码的示例输出:
keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<01b9f69b 45deb31d eda46c2d dc9ad9e8 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("Abn2m0Xesx3tpGwt3JrZ6A==")
你能告诉我为什么同一个key,iv,和string每次的输出都不一样吗?谢谢!在
你看到静脉注射了吗?这是初始化向量,它的作用是作为一个计数器,使你每次加密不同,使它更安全,更难破解。所以基本上你的代码运行得很好,但是为了正确地解密它,接收者不能只通过拥有密钥来操作,还需要IV
免责声明:我无法运行问题代码。除其他事项外,它还不完整,扩展声明丢失。它似乎是Swift 2代码,至少需要更新到Swift 3。在
加密:cryptdata
&D699D6900美元
是完全错误的,它甚至是长度错误的加密数据块大小的倍数。在
使用PKCS#7填充和CBC模式,加密结果应为:C99A30D8DA44968418E8B66F42790216。见CyyptomathicAES CALCULATOR。注意
0b0b0b0b0b0b0b0b0b0b0b
是PKCS#7填充。在下面是Swift 3中的一个例子,这是不是生产的代码,它至少缺少错误处理。在
输出:
^{pr2}$相关问题 更多 >
编程相关推荐