Skip to content

Instantly share code, notes, and snippets.

@reigelgallarde
Forked from Tiriel/encryption.js
Last active October 2, 2018 06:12
Show Gist options
  • Save reigelgallarde/60041557dbf63d0247967e2ec00bc2f0 to your computer and use it in GitHub Desktop.
Save reigelgallarde/60041557dbf63d0247967e2ec00bc2f0 to your computer and use it in GitHub Desktop.
Symetric encryption/decryption for PHP and NodeJS communication
'use strict';
const crypto = require('crypto');
const AES_METHOD = 'aes-256-cbc';
const IV_LENGTH = 16; // For AES, this is always 16, checked with php
const password = 'lbwyBzfgzUIvXZFShJuikaWvLJhIVq36'; // Must be 256 bytes (32 characters)
function encrypt(text, password) {
if (process.versions.openssl <= '1.0.1f') {
throw new Error('OpenSSL Version too old, vulnerability to Heartbleed')
}
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv(AES_METHOD, new Buffer(password), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
function decrypt(text) {
let textParts = text.split(':');
let iv = new Buffer(textParts.shift(), 'hex');
let encryptedText = new Buffer(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', new Buffer(password), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
<?php
define('AES_METHOD', 'aes-256-cbc');
$password = 'lbwyBzfgzUIvXZFShJuikaWvLJhIVq36';
function encrypt($message, $password)
{
if (OPENSSL_VERSION_NUMBER <= 268443727) {
throw new RuntimeException('OpenSSL Version too old, vulnerability to Heartbleed');
}
$iv_size = openssl_cipher_iv_length(AES_METHOD);
$iv = openssl_random_pseudo_bytes($iv_size);
$ciphertext = openssl_encrypt($message, AES_METHOD, $password, OPENSSL_RAW_DATA, $iv);
$ciphertext_hex = bin2hex($ciphertext);
$iv_hex = bin2hex($iv);
return "$iv_hex:$ciphertext_hex";
}
function decrypt($ciphered, $password) {
$iv_size = openssl_cipher_iv_length(AES_METHOD);
$iv = mb_substr($ciphered, 0, $iv_size, '8bit');
$ciphertext = mb_substr($ciphered, $iv_size+1, strlen($ciphered), '8bit');
return openssl_decrypt($ciphertext, AES_METHOD, $password, OPENSSL_RAW_DATA, $iv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment