I have 2 PHP functions to encrypt and decrypt messages/tokens and I am more-so trying to accomplish the same decrypt function rather then the encrypt function but in Node.JS.
$this->encryptMethod = 'aes-256-ctr';
$this->encryptKey = hex2bin('KEY123');
public function token_encrypt($message, $encode = false)
{
$nonceSize = openssl_cipher_iv_length($this->encryptMethod);
$nonce = openssl_random_pseudo_bytes($nonceSize);
$ciphertext = openssl_encrypt(
$message,
$this->encryptMethod,
$this->encryptKey,
OPENSSL_RAW_DATA,
$nonce
);
if ($encode) {
return base64_encode($nonce.$ciphertext);
}
return $nonce.$ciphertext;
}
public function token_decrypt($message, $encoded = false)
{
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
return false;
}
}
$nonceSize = openssl_cipher_iv_length($this->encryptMethod);
$nonce = mb_substr($message, 0, $nonceSize, '8bit');
$ciphertext = mb_substr($message, $nonceSize, null, '8bit');
$plaintext = openssl_decrypt(
$ciphertext,
$this->encryptMethod,
$this->encryptKey,
OPENSSL_RAW_DATA,
$nonce
);
return $plaintext;
}
I was able to get this far in Node.JS without getting completely lost
const hex2bin = s => s.match(/../g).map(c => String.fromCharCode(parseInt(c, 16))).join``;
function token_decrypt(message) {
var encryptionKey = Buffer.from(hex2bin("KEY123")).toString('base64');
var encryptionMethod = "aes-256-ctr";
var encrypted = Buffer.from(message, 'base64').toString();
const nonceSize = 16;
return false;
}