The iv is prefixed to the encrypted data
aesCBC128Encrypt will create a random IV and prefixed to the encrypted code. aesCBC128Decrypt will use the prefixed IV during decryption.
Inputs are the data and key are Data objects. If an encoded form such as Base64 if required convert to and/or from in the calling method.
The key should be exactly 128-bits (16-bytes). For other key sizes see the Swift 3.0 example.
PKCS#7 padding is set by default.
This example requires Common Crypto It is necessary to have a bridging header to the project: #import <CommonCrypto/CommonCrypto.h> Add the Security.framework to the project.
See Swift 3 example for notes.
This is example, not production code.
func aesCBC128Encrypt(data data:[UInt8], keyData:[UInt8]) -> [UInt8]? {
let keyLength = size_t(kCCKeySizeAES128)
let ivLength = size_t(kCCBlockSizeAES128)
let cryptDataLength = size_t(data.count + kCCBlockSizeAES128)
var cryptData = [UInt8](count:ivLength + cryptDataLength, repeatedValue:0)
let status = SecRandomCopyBytes(kSecRandomDefault, Int(ivLength), UnsafeMutablePointer<UInt8>(cryptData));
if (status != 0) {
print("IV Error, errno: \(status)")
return nil
}
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
keyData, keyLength,
cryptData,
data, data.count,
&cryptData + ivLength, cryptDataLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.removeRange(numBytesEncrypted+ivLength..<cryptData.count)
}
else {
print("Error: \(cryptStatus)")
return nil;
}
return cryptData;
}
func aesCBC128Decrypt(data data:[UInt8], keyData:[UInt8]) -> [UInt8]? {
let clearLength = size_t(data.count)
var clearData = [UInt8](count:clearLength, repeatedValue:0)
let keyLength = size_t(kCCKeySizeAES128)
let ivLength = size_t(kCCBlockSizeAES128)
var numBytesDecrypted :size_t = 0
let cryptStatus = CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
keyData, keyLength,
data,
UnsafePointer<UInt8>(data) + ivLength, data.count - ivLength,
&clearData, clearLength,
&numBytesDecrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
clearData.removeRange(numBytesDecrypted..<clearLength)
} else {
print("Error: \(cryptStatus)")
return nil;
}
return clearData;
}
Example usage:
let clearData = toData("clearData0123456")
let keyData = toData("keyData890123456")
print("clearData: \(toHex(clearData))")
print("keyData: \(toHex(keyData))")
let cryptData = aesCBC128Encrypt(data:clearData, keyData:keyData)!
print("cryptData: \(toHex(cryptData))")
let decryptData = aesCBC128Decrypt(data:cryptData, keyData:keyData)!
print("decryptData: \(toHex(decryptData))")
Example Output:
clearData: <636c6561 72446174 61303132 33343536>
keyData: <6b657944 61746138 39303132 33343536>
cryptData: <9fce4323 830e3734 93dd93bf e464f72a a653a3a5 2c40d5ea e90c1017 958750a7 ff094c53 6a81b458 b1fbd6d4 1f583298>
decryptData: <636c6561 72446174 61303132 33343536>