Encrypt in PHP 7 decrypt in Node JS - php

In PHP 5.6 there were plenty of solutions that worked perfectly that were based on http://php.net/manual/en/function.mcrypt-decrypt.php
For example
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));
}
But PHP7 has a WARNING that discourages using this function.
"This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged."
Any ideas for safe encryption using keywords on both ends; PHP + Node.js?

LibMcrypt was abandoned in 2007. More information https://wiki.php.net/rfc/mcrypt-viking-funeral
You have to use openssl encrypt http://php.net/manual/en/function.openssl-encrypt.php
PHP
<?php
$textToEncrypt = "Secret Text to Encrypt";
$encryptionMethod = 'aes-256-cbc';
$secretHash = "315a5504d921f8327f73a356d2bbcbf1"; // <---- you have to use some persistent key.
$iv_size = openssl_cipher_iv_length($encryptionMethod);
$iv = openssl_random_pseudo_bytes($iv_size);
//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash, 0, $iv);
//Concatenate iv with data
$encryptedMessageWithIv = bin2hex($iv) . $encryptedMessage;
//To Decrypt
$iv_size = openssl_cipher_iv_length($encryptionMethod);
$iv = hex2bin(substr($encryptedMessageWithIv, 0, $iv_size * 2));
$decryptedMessage = openssl_decrypt(substr($encryptedMessageWithIv, $iv_size * 2), $encryptionMethod, $secretHash, 0, $iv);
echo "Encrypted: $encryptedMessageWithIv <br>Decrypted: $decryptedMessage";
Try it here https://3v4l.org/r9pYv
Node.JS(i really not a node.js programmer, there can be more efficient way)
var data = "ad699a2537ec2a7f699acbf97ca0080eh3z5EgvnTAvlc76YeR6HdWPmkDDt+pHiG//qo7xnqyQ=";
var key = "315a5504d921f8327f73a356d2bbcbf1";
var iv = new Buffer(data.substring(0,32), 'hex');
var dec = crypto.createDecipheriv('aes-256-cbc',key,iv);
var decrypted = Buffer.concat([dec.update(new Buffer(data.substring(32),'base64')), dec.final()]);
console.log('DECRYPTED TEXT: '+decrypted.toString());
Try here: https://repl.it/FQyo/2

Related

Converting PHP encryption to NodeJS

I'm currently implementing encryption on my API. I have to implement this the same way it is encrypted and decrypted in a specific script written in PHP.
This works all fine when I output the result in, let's say, base64. The PHP decrypt method runs against it and works just fine. The problem is that I need to output not in base64 but in binary due to certain requirements, but when I encrypt from the Nodejs side into binary the result is different than when I encrypt in the PHP into binary when it should be the same.
PHP Encryption:
function vd_encrypt($plaintext, $password) {
$method = "AES-256-CBC";
$key = hash('sha256', $password, true);
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
$hash = hash_hmac('sha256', $ciphertext, $key, true);
return $iv . $hash . $ciphertext;
}
Javascript Encryption:
import crypto from 'crypto';
export function encrypt (plain_text: string): string {
const encryptionMethod = 'AES-256-CBC';
const iv = crypto.randomBytes(IV_LENGTH);
const key = crypto.createHash("sha256").update(secret).digest();
var encryptor = crypto.createCipheriv(encryptionMethod, key, iv);
const result = iv + encryptor.update(plain_text, 'utf8', 'binary') + encryptor.final('binary');
return result;
}
I've updated your code slightly to accept an iv parameter. You can generate this in the same way as before (e.g. openssl_random_pseudo_bytes).
For the purposes of demonstration I'll use a fixed IV so we can show the same result.
PHP
function vd_encrypt($plaintext, $password, $iv) {
$method = "AES-256-CBC";
$key = hash('sha256', $password, true);
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
$hash = hash_hmac('sha256', $ciphertext, $key, true);
return $iv . $hash . $ciphertext;
}
// Replace with below code in production
// $iv = openssl_random_pseudo_bytes(16);
$iv = base64_decode("eQMrc61Gt8qRejRjhJOkVw==");
$result = vd_encrypt("He was a man take him for all in all, I shall not look upon his like again", "password", $iv);
echo "Result (base64): " . base64_encode($result) . "\n";
Node.js
import crypto from 'crypto';
export function encrypt (plaintext: string, password: string, iv: string): string {
const encryptionMethod = 'AES-256-CBC';
const key = crypto.createHash("sha256").update(password).digest();
const encryptor = crypto.createCipheriv(encryptionMethod, key, iv);
const encryptedData = Buffer.concat([encryptor.update(plaintext, 'utf8'), encryptor.final()]);
const hash = crypto.createHmac("sha256", key).update(encryptedData).digest();
return Buffer.concat([iv, hash, encryptedData]);
}
// Replace with below code in production
//const iv = crypto.randomBytes(16);
const iv = Buffer.from("eQMrc61Gt8qRejRjhJOkVw==", "base64");
const result = encrypt("He was a man take him for all in all, I shall not look upon his like again", "password", iv);
console.log("Result (base64):", result.toString("base64"));
In this case the results will be like so:
PHP:
Result (base64): eQMrc61Gt8qRejRjhJOkVxsqZTqUjSUnaL46yZDLGGK5+o7WKLyIiG4UKj0ST93Wi7UlaAyTFIjpIs0C893SFsnHeuVshG+6EJF99GrLSUCMFJG3J1pJnmxF4Pu8ZCbN7Ounp0BjhJKIpu9yQn6uEYylJLXWpzNw+aCwsnIV1h0=
Node.js:
Result (base64): eQMrc61Gt8qRejRjhJOkVxsqZTqUjSUnaL46yZDLGGK5+o7WKLyIiG4UKj0ST93Wi7UlaAyTFIjpIs0C893SFsnHeuVshG+6EJF99GrLSUCMFJG3J1pJnmxF4Pu8ZCbN7Ounp0BjhJKIpu9yQn6uEYylJLXWpzNw+aCwsnIV1h0=

php: how to generate different output for same string

Is there some way to generate different output for same given string, here is example:
echo md5('test');
That always generates same fb469d7ef430b0baf0cab6c436e70375 for the given input. How do I generate different encrypted text each time and be able to decrypt it later if needed ?
I have seen functions such as md5, base64_encode, crypt, sha1, etc but they generate same output and secondly I cannot decrypt later if needed.
P.S: I know I can go with one way encryption and compare encrypted texts but for a particular scenario, I have requirement to be able to decrypt text completely if needed later however I am not able to figure out if there is some way or function in php for it.
Any help will be greatly appreciated. Thanks
To encrypt the same plaintext so that it generates different ciphertext you change the key (and/or Initialization Vector (IV) depending on the mode of the algorithm, like CBC).
Example:
$string = 'Some Secret thing I want to encrypt';
$iv = '12345678';
$passphrase = '8chrsLng';
$encryptedString = encryptString($string, $passphrase, $iv);
// Expect: 7DjnpOXG+FrUaOuc8x6vyrkk3atSiAf425ly5KpG7lOYgwouw2UATw==
function encryptString($unencryptedText, $passphrase, $iv) {
$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
Both the same IV and the passphrase must be used when decrypting in CBC mode. The passphrase MUST be kept a secret (from eavesdroppers) while the IV can be transmitted in the clear.
You CAN (but should not) use the same passphrase for every message/data but you should ALWAYS change the IV for each message/data.
This is the basics of encryption but depending on you needs you may need to modify your architecture to keep the system secure.
md5 is a hash method, not an encryption.
in short. there is no "good" way back from md5.
base64_encode and base64_decode and be used to transport messages, but it is no decryption.
please google on the topic RSA, ROT-13 or basic encryption with php.
I have created this class (Thanks to #Sani Huttunen for the idea) for the purpose. It allows to have differ text generated each time even for same input text and decodes it successfully as well.
class Encoder
{
private static $prefix = '#!#';
public static function php_aes_encrypt($text, $key)
{
if (!trim($text)) {
return '';
}
$iv = self::generateRandomString();
$key = self::mysql_aes_key($key);
$pad_value = 16 - (strlen($text) % 16);
$text = str_pad($text, (16 * (floor(strlen($text) / 16) + 1)), chr($pad_value));
$ciphertext = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$key,
$text,
MCRYPT_MODE_CBC,
$iv
);
$ciphertext = self::getPrefix() . base64_encode($ciphertext . $iv);
return $ciphertext;
}
public static function php_aes_decrypt($text, $key)
{
$text = str_replace(self::getPrefix(), '', $text);
$text = base64_decode($text);
if (!trim($text)) {
return '';
}
$iv = substr($text, -16);
$text = str_replace($iv, '', $text);
$key = self::mysql_aes_key($key);
$text = mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
$key,
$text,
MCRYPT_MODE_CBC,
$iv
);
return rtrim($text, "\0..\16");
}
private static function mysql_aes_key($key)
{
$new_key = str_repeat(chr(0), 16);
for ($i = 0, $len = strlen($key); $i < $len; $i ++) {
$new_key[$i % 16] = $new_key[$i % 16] ^ $key[$i];
}
return $new_key;
}
private static function getPrefix()
{
return base64_encode(self::$prefix);
}
public static function isEncrypted($ciphertext)
{
$isEncrypted = (false !== strpos($ciphertext, self::getPrefix()));
return $isEncrypted;
}
private static function generateRandomString()
{
return substr(sha1(rand()), 0, 16);
}
}
Usage:
$encrypted = Encoder::php_aes_encrypt('my test string', 'key');
echo $encrypted . '<br>';
echo Encoder::php_aes_decrypt($encrypted, 'key');

PHP code to encrypt using 3DES algorithm using CBC mode and a secretkey and IV spec key

i am try to encrypt following data using the 3des(CBC) using a secretkey and IV spec key in php but i am not getting the same output which i get on this online tool (http://symmetric-ciphers.online-domain-tools.com/)
//input
$data = "Id=120278;timestamp=2009-02-05 08:28:39.195";
$key = "80127ECD5E40BB25DB14354A3795880DF2B459BB08E1EE6D";
$iv = "331BA9C5A7446C98";
//output from online tool. I should get the same result in my php code
$result = "1C80CBCE1713128176499C7A3DFB8779156B31B8DEF2F667A7100F1C3AEFABACB24283CFDF 5D312D A0074897138684BC";
following the PHP code i tried
$string = "Id=120278;timestamp=2009-02-05 08:28:39.195";
$iv = "331BA9C5A7446C98";
$passphrase = "80127ECD5E40BB25DB14354A3795880DF2B459BB08E1EE6D";
$encryptedString = encryptString($string, $passphrase, $iv);
function encryptString($unencryptedText, $passphrase, $iv) {
$enc = mcrypt_encrypt(MCRYPT_3DES, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
Try this:
function encrypt3DES($key,$iv,$text_enc){
$block = mcrypt_get_block_size('tripledes', 'cbc');
$pad = $block - (strlen($text_enc) % $block);
$text_enc .= str_repeat(chr($pad), $pad);
$text_enc = mcrypt_encrypt(MCRYPT_3DES, $key, $text_enc, MCRYPT_MODE_CBC, $iv);
$text_enc = base64_encode ($text_enc);
return $text_enc;
}

PHP Encrypt Data, Bash Decrypt it

I am trying to come up with a way to have PHP encrypt a file. I used to just use a PHP system call to run a script that encoded the file:
#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -salt -k $1 -in $2
Argument 1 was the password to use and argument 2 is the data. I then use a second script on a computer to de-crypt the file.
#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -d -salt -k $1 -in $2
This method of encrypting will not work on a production host as the PHP system call is disabled. I also would prefer not the change the decode function if at all possible.
Is there a way to replicate the above encrypt function using only PHP?
Take a look at mcyrpt_encrypt():
string mcrypt_encrypt ( string $cipher , string $key , string $data ,
string $mode [, string $iv ] )
Set $cipher to MCRYPT_RIJNDAEL_128 (AES-128), and $mode to MCRYPT_MODE_CBC.
Then use base64_encode() to generate a base-64 encoded output (ie: what the -a option
does).
openssl derives the key and IV as follows:
Key = MD5(Password + Salt)
IV = MD5(Key + Password + Salt)
Where Salt is a 8 byte salt. With this in mind, I created simple encrypt() and decrypt() routines:
function ssl_encrypt($pass, $data) {
$salt = substr(md5(mt_rand(), true), 8);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$ct = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $data,
MCRYPT_MODE_CBC, $iv);
return base64_encode('Salted__' . $salt . $ct);
}
function ssl_decrypt($pass, $data) {
$data = base64_decode($data);
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$pt = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $ct,
MCRYPT_MODE_CBC, $iv);
return $pt;
}
The parameter $data takes the string to be encrypted. If you want to encrypt a file, you'll have to get it via file_get_contents() or similar and then give that to the function.
Usage:
echo ssl_encrypt('super secret key', 'Hello World');
Generates something like (will change every time because of the random salt):
U2FsdGVkX18uygnq8bZYi6f62FzaeAnyB90U6v+Pyrk=
As stated above in the comments padding is necessary to make this work. The function below will make a file that can be decrypted on the command line like this:
openssl enc -d -aes-256-cbc -a -salt -in test.txt
The test.txt file is created from the output of the ssl_encrypt function below.
function ssl_encrypt($pass, $data)
{
// Set a random salt
$salt = substr(md5(mt_rand(), true), 8);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data = $data . str_repeat(chr($pad), $pad);
// Setup encryption parameters
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
$key_len = mcrypt_enc_get_key_size($td);
$iv_len = mcrypt_enc_get_iv_size($td);
$total_len = $key_len + $iv_len;
$salted = '';
$dx = '';
// Salt the key and iv
while (strlen($salted) < $total_len)
{
$dx = md5($dx.$pass.$salt, true);
$salted .= $dx;
}
$key = substr($salted,0,$key_len);
$iv = substr($salted,$key_len,$iv_len);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return chunk_split(base64_encode('Salted__' . $salt . $encrypted_data),32,"\r\n");
}
Example Usage:
$plainText = "Secret Message";
$password = "SecretPassword";
$test = ssl_encrypt($password, $plainText);
$file = fopen('test.txt', 'wb');
// Write the Base64 encrypted output to a file.
fwrite($file, $test);
fclose($file);
// Show the output on the screen
echo $test;
References: http://juan.boxfi.com/2010/03/16/write-openssl-files-in-php/
Perhaps PHP's OpenSSL library?

Decrypt string in php which was encrypted with aspEncrypt

I need to communicate with a asp platform that uses the aspEncrypt from persits.
Can anyone provide an example how to decode a string with PHP and mcrypt that was created via the aspEncrypt routines.
An example page of aspEncrypt is available at this link:
http://support.persits.com/encrypt/demo_text.asp
So if I use the text "Test" and the key "test" it provides an base64 encoded string. I need a php example that convert this encoded string back to the text "Test" with usage of key "test".
This is how i finally solved it:
Expectation:
Key is known
IV is known (in my case, first 32 characters of encoded data)
Encrypted Text is known
In my special case all received data hex encoded.
This means IV and encrypted text.
function decrypt($sString, $sIv, $sKey, $iCipherAlg) {
$sDecrypted = mcrypt_decrypt($iCipherAlg, $sKey, $sString, MCRYPT_MODE_CBC, $sIv);
return trim($sDecrypted);
}
function hex2bin($sData) {
$iLen = strlen($sData);
$sNewData = '';
for($iCount=0;$iCount<$iLen;$iCount+=2) {
$sNewData .= pack("C",hexdec(substr($sData,$iCount,2)));
}
return $sNewData;
}
$sKey = 'this is my key';
// first 32 chars are IV
$sIv = hex2bin(substr($sEncodedData, 0, 32));
$sEncodedData = substr($sEncodedData, 32);
$sEncodedRaw = hex2bin($sEncodedData);
$sDecrypted = decrypt($sEncodedRaw, $sIv, $sKey, MCRYPT_RIJNDAEL_128);
A corresponding encryption works like that:
$sIv = mcrypt_create_iv(mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
$sKey = 'this is my key';
$sContent = 'a lot of content';
$sEncrypted = bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $sKey, $sContent, MCRYPT_MODE_CBC, $sIv));
$sFullEncodedText = bin2hex($sIv) . $sEncrypted;
I encountered an old VBScript project which was encrypting strings with AspEncrypt like this:
Function EncryptString(data, base64Iv)
Set CM = Server.CreateObject("Persits.CryptoManager")
Set Context = CM.OpenContextEx("Microsoft Enhanced RSA and AES Cryptographic Provider", "", True)
Set Key = Context.GenerateKeyFromPassword("secret encryption password", calgSHA512, calgAES256)
Set IVblob = CM.CreateBlob
IVblob.Base64 = base64Iv
Key.SetIV IVblob
Set Blob = Key.EncryptText(data)
EncryptString = Blob.Base64 & ":" & base64Iv
End Function
Based on the arguments to GenerateKeyFromPassword, a binary key is created by hashing the password with SHA-512, and data is encrypted with the aes-256-cbc algorithm. The random Base64-encoded initialization vector is appended to the encrypted value after a colon.
This can be replicated in PHP using the OpenSSL extension:
class Aes256Cbc
{
private string $algo = 'aes-256-cbc';
private string $key;
private int $ivLen;
public function __construct(string $password)
{
$this->key = hash('sha512', $password, true);
$this->ivLen = openssl_cipher_iv_length($this->algo);
}
public function encrypt(string $data): string
{
$iv = random_bytes($this->ivLen);
$ciphertext = openssl_encrypt($data, $this->algo, $this->key, OPENSSL_RAW_DATA, $iv);
return base64_encode($ciphertext) . ':' . base64_encode($iv);
}
public function decrypt(string $encrypted): string
{
[$ctPart, $ivPart] = explode(':', $encrypted);
$iv = base64_decode($ivPart);
$ciphertext = base64_decode($ctPart);
return openssl_decrypt($ciphertext, $this->algo, $this->key, OPENSSL_RAW_DATA, $iv);
}
}
Example usage:
$aes = new Aes256Cbc("secret encryption password");
$decrypted = $aes->decrypt($someValue);
Note: if AspEncrypt was used without setting an initialization vector, the IV will be sequence of null bytes. This fixed IV could be generated in the above PHP class as follows:
$iv = str_repeat("\0", $this->ivLen);
It depends on which cipher it uses, take a look at mcrypt as long as you know the cipher and key it should be easy to decrypt.
If you know the cipher and mode used by the encryption, the function mcrypt_decrypt can decrypt it.
http://uk3.php.net/manual/en/function.mcrypt-decrypt.php

Categories