Skip to content

Instantly share code, notes, and snippets.

@daohoangson
Last active December 3, 2017 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daohoangson/a4fe0b9ed5ee7911c77c007bbf3beff9 to your computer and use it in GitHub Desktop.
Save daohoangson/a4fe0b9ed5ee7911c77c007bbf3beff9 to your computer and use it in GitHub Desktop.
AES128 CBC encryption
// input
const secret = 'top secret'
const userData = {'version_id': 1, 'user_id': 123, 'username': 'xxx'}
// prepare
const password = crypto.createHash('md5').update(secret).digest()
const json = JSON.stringify(userData)
const cipher = 'aes-128-cbc'
const ivLength = 16
// encryption
const iv = crypto.randomBytes(ivLength)
const jsonBuffer = Buffer.from(json, 'binary')
const cipherObj = crypto.createCipheriv(cipher, password, iv)
const encrypted = Buffer.concat([cipherObj.update(jsonBuffer), cipherObj.final()])
const encoded = Buffer.concat([iv, encrypted]).toString('base64')
console.log('encoded = ', encoded)
// decryption
const decoded = Buffer.from(encoded, 'base64')
const decryptIv = Buffer.alloc(ivLength)
decoded.copy(decryptIv, 0, 0)
const encryptedNoIv = Buffer.alloc(decoded.length - ivLength)
decoded.copy(encryptedNoIv, 0, ivLength)
const decipherObj = crypto.createDecipheriv(cipher, password, decryptIv)
const decrypted = Buffer.concat([decipherObj.update(encryptedNoIv), decipherObj.final()])
console.log('decrypted = ', decrypted.toString())
<?php
// input
$secret = 'top secret';
$userData = ['version_id' => 1, 'user_id' => 123, 'username' => 'xxx'];
// prepare
$password = md5($secret, true);
$json = json_encode($userData);
$cipher = 'aes128';
$ivLength = openssl_cipher_iv_length($cipher);
// encryption
$iv = openssl_random_pseudo_bytes($ivLength);
$encrypted = openssl_encrypt($json, $cipher, $password, OPENSSL_RAW_DATA, $iv);
printf("strlen(\$encrypted) = %d\n", strlen($encrypted));
$encoded = base64_encode($iv . $encrypted);
printf("encoded = %s\n", $encoded);
// decryption
$decoded = base64_decode($encoded);
$iv = mb_substr($decoded, 0, $ivLength, '8bit');
$encryptedNoIv = mb_substr($decoded, $ivLength, null, '8bit');
$decrypted = openssl_decrypt($encryptedNoIv, $cipher, $password, OPENSSL_RAW_DATA, $iv);
printf("decrypted = %s\n", $decrypted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment