如何使用aes模式加密swift中的字符串?

时间:2015-04-07 07:27:48

标签: php ios swift

我在网上搜索了很多文章,但却找不到 [iOS 3DES with ECB return half correct data 在Stackoverflow上,但是当我复制本文中的代码时,编译器会返回与在线加密工具中获得的不同的加密结果。

任何人都可以帮助我吗?
感谢

另外,我无法真正阅读obj-c。刚从javascriptPHP开始转向。

===========编辑===========

现在,我使用swift 1.2将我的方法更改为AES。代码如下所示(iv和密钥保持静态以进行测试):

    let key:String = "12345678901234567890123456789012"
    let iv:String =  "12345678901234567890123456789012"

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

    let plainData: NSData! = (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:   CCOptions = UInt32(kCCOptionPKCS7Padding)

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

    var numBytesEncrypted: size_t = 0

    var cryptStatus = CCCrypt(operation, algoritm, options, keyBytes, keyLength, ivPointer, dataBytes, dataLength, bufferPointer, bufferLength, &numBytesEncrypted)

这是我的PHP代码:

    function addPkcs7Padding($string) {
        $cipher = MCRYPT_RIJNDAEL_256;
        $mode = MCRYPT_MODE_CBC;
        $blocksize = mcrypt_get_iv_size($cipher, $mode);
        $len = strlen($string);
        $pad = $blocksize - ($len % $blocksize);
        $string .= str_repeat(chr($pad), $pad);
        return $string;
    }

    function aes256cbcEncrypt($str, $iv, $key ) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addPkcs7Padding($str) , MCRYPT_MODE_CBC, $iv));
    }

1 个答案:

答案 0 :(得分:0)

  1. 您没有将加密数据的长度设置为引用返回的值:numBytesEncrypted。在这种情况下:bufferData.length = numBytesEncrypted

  2. MCRYPT_RIJNDAEL_256指定256位的块大小,AES仅使用128的块大小,将mcrypt中的大小更改为MCRYPT_RIJNDAEL_128。注意:块大小与密钥大小不同。

  3. iv大小是块大小(128位/ 16字节)。

  4. 显示示例输入和输出数据以获得更多帮助。

  5. 对于Swift示例SO answer: