简体   繁体   中英

AES 128 Decryption with CBC mode in iOS Swift

I am using CommonCrypto to decrypt an encrypted MP3 file getting from server. Actually the server side uses AES 128 bit encryption with CBC mode and PKCS5Padding .So I want to decrypt it in the same manner.

I use the code below for decryption.

    #import <CommonCrypto/CommonCrypto.h

func testCrypt(data:NSData, keyData:NSData, ivData:NSData, operation:CCOperation) -> NSData? {
    let keyBytes = UnsafePointer<UInt8>(keyData.bytes)
    print("keyLength   = \(keyData.length), keyData   = \(keyData)")

    let ivBytes = UnsafePointer<UInt8>(ivData.bytes)
    print("ivLength    = \(ivData.length), ivData    = \(ivData)")

    let dataLength = Int(data.length)
    let dataBytes  = UnsafePointer<UInt8>(data.bytes)
    print("dataLength  = \(dataLength), data      = \(data)")

    let cryptData: NSMutableData! = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
    let cryptPointer = UnsafeMutablePointer<UInt8>(cryptData.mutableBytes)
    let cryptLength  = size_t(cryptData.length)

    let keyLength              = size_t(kCCKeySizeAES128)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
    let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)

    var numBytesEncrypted :size_t = 0

    let cryptStatus = CCCrypt(operation,
        algoritm,
        options,
        keyBytes, keyLength,
        ivBytes,
        dataBytes, dataLength,
        cryptPointer, cryptLength,
        &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)
        print("cryptLength = \(numBytesEncrypted), cryptData = \(cryptData)")

    } else {
        print("Error: \(cryptStatus)")
    }

    return cryptData;
}

How can I specify the CBC mode and PKCS5Padding in this code?

Thanks in advance

The Block size of AES using always 16 bytes . And block size of PKCS5Padding is defined 8 byte . so you can not use the combination like AES/CBC/PKCS5Padding . you can only use PKCS5Padding when your block size is not more than 8 bytes.

Another things

CCCrypt is default working on CBC mode , so in that case you do not need to mention CBC mode . As instance , If you want to ECB mode that time you should mentioned kCCOptionECBMode

Unfortunately Apple documentation do not have PKCS5Padding . You can use PKCS7Padding alternative of PKCS5Padding when your block size will exactly 8 bytes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM