1

Wanted to convert the following Node Crypto example to equivalent Swift commonCrypto:

function encrypt(key, text){
    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    let final_encrypted = iv.toString('hex') + ':' + encrypted.toString('hex');

    console.log(final_encrypted);    // <-- final encrypted string
}

function decrypt(key, enc_text){
    let textParts = enc_text.split(':');
    let iv = Buffer.from(textParts.shift(), 'hex');
    let encryptedText = Buffer.from(textParts.join(':'), 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
    let decrypted = decipher.update(encryptedText);
    let final = decipher.final();
    decrypted = Buffer.concat([decrypted, final]);


    console.log(decrypted.toString());     // <-- final decrypted string
}

Swift implementation code is posted here: Swift AES encryption using CommonCrypto

Nah
  • 1,690
  • 2
  • 26
  • 46
  • 1
    What have you tried yourself so far? – 404 Jul 18 '21 at 14:12
  • 1
    StackOverflow is not a code conversion service and you should ask for a certain problem. How to implement AES 256 with CBC you can look at this answer: https://stackoverflow.com/a/37681510/979986 – iUrii Jul 20 '21 at 11:15
  • I just updated the question with Swift code snippet reference. – Nah Aug 21 '21 at 17:01

0 Answers0