AES加密&斯威夫特解密

时间:2016-04-29 21:15:53

标签: swift aes

我想使用AES算法加密和解密Swift中的文本,该算法应与Android和PHP加密算法兼容。所以,我一直在试用question here中的代码,但结果什么都没打印出来。这是与原始代码相比几乎没有修改的代码:

    var key = "abcdefghijklmnopqrstuvwxyz012345"
    var iv = "0000000000000000"
    var plainText = "Hello World"

    let keyData: NSData! = (key as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
    let keyBytes         = UnsafePointer<UInt8>(keyData.bytes)
    let keyLength        = size_t(kCCKeySizeAES256)

    let plainData = (plainText as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
    let dataLength    = size_t(plainData.length)
    let dataBytes     = UnsafePointer<UInt8>(plainData.bytes)

    var bufferData    = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
    var bufferPointer = UnsafeMutablePointer<UInt8>(bufferData!.mutableBytes)
    let bufferLength  = size_t(bufferData!.length)

    let operation: CCOperation = UInt32(kCCEncrypt)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
    let options = UInt32(kCCOptionPKCS7Padding)

    let ivData: NSData! = (iv as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
    let ivPointer = UnsafePointer<UInt8>(ivData.bytes)

    var numBytesEncrypted: UnsafeMutablePointer<Int> = nil
    var cryptStatus = CCCrypt(operation, algoritm, options, keyBytes, keyLength, ivPointer, dataBytes, dataLength, bufferPointer, bufferLength, numBytesEncrypted)

    bufferData!.length = numBytesEncrypted.hashValue
    let base64cryptString = bufferData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
    print(base64cryptString)

我错过了什么吗?请帮忙!如果您知道如何解决它或获得一些适用于AES加密的代码。解密我会很感激的。

0 个答案:

没有答案