2

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.

javierdemartin
  • 595
  • 6
  • 24
  • what do you mean it's not the result you expect do you mean the cipher text is not matching PHP's output? – Woodstock Nov 29 '19 at 09:46
  • Yes, modified the title – javierdemartin Nov 29 '19 at 09:52
  • Why would it match, if you use a different IV or key, the cipher text will be different... I suspect thats the issue can you print the two IV's and Keys and check they are identical – Woodstock Nov 29 '19 at 09:54
  • I have specified in my question that both PHP and Swift's Key and IV match – javierdemartin Nov 29 '19 at 09:56
  • The implementations of AES may also differ, I wouldn't use CryptoSwift, choose libsodium or CryptoKit instead. If everything is identical I suspect it's an implementation subtlety. – Woodstock Nov 29 '19 at 09:56

0 Answers0