Skip to content

Instantly share code, notes, and snippets.

@shelan
Forked from rojan/node_crypto.js
Created February 17, 2016 11:52
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 shelan/72a8a8458cd2a9d38690 to your computer and use it in GitHub Desktop.
Save shelan/72a8a8458cd2a9d38690 to your computer and use it in GitHub Desktop.
Encrypt in nodejs and decrypt in php or vice versa
var crypto = require('crypto');
var key = 'MySecretKey12345';
var iv = '1234567890123456';
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
var text = 'plain text';
var encrypted = cipher.update(text, 'utf8', 'binary');
encrypted += cipher.final('binary');
hexVal = new Buffer(encrypted, 'binary');
newEncrypted = hexVal.toString('hex');
console.log('Encrypted: ', newEncrypted);
var decrypted = decipher.update(newEncrypted, 'hex', 'binary');
decrypted += decipher.final('binary');
console.log('Decrypted: ', decrypted);
<?php
class Crypto
{
private $encryptKey = 'MySecretKey12345';
private $iv = '1234567890123456';
private $blocksize = 16;
public function decrypt($data)
{
return $this->unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
$this->encryptKey,
hex2bin($data),
MCRYPT_MODE_CBC, $this->iv), $this->blocksize);
}
public function encrypt($data)
{
//don't use default php padding which is '\0'
$pad = $this->blocksize - (strlen($data) % $this->blocksize);
$data = $data . str_repeat(chr($pad), $pad);
return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
$this->encryptKey,
$data, MCRYPT_MODE_CBC, $this->iv));
}
private function unpad($str, $blocksize)
{
$len = mb_strlen($str);
$pad = ord( $str[$len - 1] );
if ($pad && $pad < $blocksize) {
$pm = preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str);
if( $pm ) {
return mb_substr($str, 0, $len - $pad);
}
}
return $str;
}
}
$crypto = new Crypto();
$text = 'plain text';
$encrypted = $crypto->encrypt($text);
//$encrypted = '9eb6c9052d1de4474fb52d829360d5af';
echo "Encrypted: ".$encrypted."\n";
$decrypted = $crypto->decrypt($encrypted);
echo "Decrypted: $decrypted\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment