swiftencryptioncryptojscryptoswift

AES encryption using CryptoSwift and CryptoJS


I was to trying encrypt a text using CryptoSwift for ios application, and CryptoJS for web application, which has to be decrypted in Java platform. I could able to encrypt successfully in javascript by using the following code.

var message = "Hello"
var password = "samplepasswordky"

function encrypt(message, password) {
  var salt = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
  var key = CryptoJS.PBKDF2(pass, salt, {
    keySize: keySize/32,
    iterations: iterations
  });

  var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
  var encrypted = CryptoJS.AES.encrypt(msg, key, {
    iv: iv
  });
  var encryptedMessage = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  return encryptedMessage;
}

For the same in CryptoSwift I am doing the following, but I could not decrypt the text in Java.

let salt: [UInt8] = Array("0000000000000000".utf8)
let password: [UInt8] = Array("samplepasswordky".utf8)
let iv: [UInt8] = Array("0000000000000000".utf8)
let derivedKey = try! PKCS5.PBKDF2(password: password, salt: salt , iterations: 100, keyLength: 16, variant: .sha1).calculate()
let encrypted = try! AES(key: derivedKey, blockMode: CBC(iv: iv), padding: .pkcs5).encrypt(input)
print(encrypted.toHexString())

Kindly help me to make this work.


Solution

  • This line:

    var salt = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
    

    Is not the same as this line:

    let salt: [UInt8] = Array("0000000000000000".utf8)
    

    The utf8 encoding of "0000000000000000" is, in hex, 30303030303030303030303030303030 (0x30 is the UTF-8 encoding of the character "0").

    What you meant to use here is Array(repeating: UInt8(0), count: 16).

    You're also outputting a Base64 string in JavaScript, and a hex string in Swift, which are not the same things.

    Unrelated side-note:

    This implementation is working pretty hard to get little security. If your password is static, you could do much better by using a random key (i.e. 32 completely random bytes 0-255, not a string of characters). PKBDF2 isn't really buying you much here, excepting slowing down the system (not slowing down the attacker; just your app). Adding a random IV would significantly improve this system as well with little cost.