I am having trouble translating code from my PHP backend to Swift using CryptoSwift. It's AES-256-CBC but either I get an invalidKeySize
error or the output produced does not match with the expected output.
My PHP code would be,
$string = "MyStringToEncrypt";
$secret_key = sha1('MySecretKey');
$secret_iv = sha1('MySecretIV');
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ));
return $output;
As far as I know I need a 16 Bytes IV and a 32 Bytes Key as it's 256 encryption. My attempt at writing this with swift is,
import CryptoSwift
let secretKey = "MySecretKey".sha1()
let secretIv = "MySecretIV".sha1()
let keyString: String = String(secretKey.sha256().prefix(32))
let ivString: String = String(secretIv.sha256().prefix(16))
let data = "MyStringToEncrypt".data(using: String.Encoding.utf8)
var result = ""
do {
let enc = try AES(key: key, iv: iv).encrypt(data!.bytes)
let encData = NSData(bytes: enc, length: Int(enc.count))
let base64String: String = encData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0));
result = String(base64String)
} catch {
print("Error \(error)")
}
This would give me a 32 Bytes Key but the result it's not the expected I get from PHP. If I don't add the .prefix(32)
I wouldn't get the 32 Bytes length key and that would give an invalid key size error.