cccrypt在swift 4中生成奇怪的输出

时间:2018-06-11 15:20:25

标签: swift cryptography swift4 commoncrypto

我尝试编写基于CCCrypt的加密(AESCBC256)函数,CCCrypt正在生成一个随机值。

例如,当我通过1234567运行时,它将返回“HlFP2rCmycZS1269Cm47Q ==”或“TTuSJrBcsOmOCDHc5IQ8Dw ==”作为相同的iv和Key。

这是iv:b5f89591 关键是:366e9c1b4b2ed2b1daf751d7500aaa01

func encrypt(Value: String)->String{
    let keyData = keyString.data(using: .utf8, allowLossyConversion: false)!
    let iv = SecretKey.data(using: .utf8, allowLossyConversion: false)!
    let message       = SecretKey+Value
    let data = message.data(using: .utf8, allowLossyConversion: false)!
    let cryptData    = NSMutableData(length: Int(data.count) + kCCBlockSizeAES128)!
    let keyLength              = size_t(kCCKeySizeAES256)
    let operation: CCOperation = CCOperation(UInt32(kCCEncrypt))
    let algoritm:  CCAlgorithm = CCAlgorithm(UInt32(kCCAlgorithmAES128))
    let options:   CCOptions   = CCOptions(UInt32(kCCOptionPKCS7Padding))
    var numBytesEncrypted :size_t = 0
    let cryptStatus = CCCrypt(operation,
                              algoritm,
                              options,
                              keyData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              keyLength,
                              iv.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              data.count,
                              cryptData.mutableBytes, cryptData.length,
                              &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)
        return String(describing: cryptData.base64EncodedString(options: .lineLength64Characters))
    }else{
        return ""
    }
}

1 个答案:

答案 0 :(得分:2)

你的IV是错误的长度。它长8个字节,但AES要求16字节IV,因此它会从内存中读取随机数据以获得其他8个字节。