I have a next problem
On Node.js I have a next code
var iv = CryptoJS.enc.Hex.parse('00000000000000000000000000000000'); //it's for tests, later it will be dynamically generated
var key256Bits = 'A5178B6A965AACF3CD60B07A15061719';
var cipher = CryptoJS.AES.encrypt(
'Some text',
key256Bits,
{
iv: iv,
padding:CryptoJS.pad.ZeroPadding
}
).toString();
Then when I try to decode it with phpseclib
$key = 'A5178B6A965AACF3CD60B07A15061719';
$data = /*text encrypted by JS*/;
$cipher = new AES();
$cipher->setKeyLength(256);
$cipher->setKey($key);
$res = $cipher->decrypt($data);
And then $res becomes an empty string
What do I do wrong?
If you pass in a string to CryptoJS.<cipher>.encrypt as a key, CryptoJS treats it as a password and will derive the actual key from that using OpenSSL's EVP_BytesToKey with a random salt and one iteration of MD5.
phpseclib doesn't have an implementation of that, so you could just pass in the actual key:
var key256Bits = CryptoJS.enc.Utf8.parse('A5178B6A965AACF3CD60B07A15061719');
Since this key is only 32 hexits long, it only has 128 bit of entropy, but still uses AES-256. You need 64 hexits which you can decode before use to get 32 bytes for a secure key size.
Also, phpseclib implements PKCS#7 padding, so you need to use
padding: CryptoJS.pad.Pkcs7
in CryptoJS.
Example JavaScript code:
var iv = CryptoJS.enc.Hex.parse('00000000000000000000000000000000'); //it's for tests, later it will be dynamically generated
var key256Bits = CryptoJS.enc.Utf8.parse('A5178B6A965AACF3CD60B07A15061719');
var cipher = CryptoJS.AES.encrypt(
'Some text',
key256Bits,
{
iv: iv,
padding: CryptoJS.pad.Pkcs7
}
).toString();
console.log(cipher)
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
In PHP, you need to make sure to decode the ciphertext before use:
$data = base64_decode("IWkBG3A46rNrxwWN2JD7xQ==");
$key = 'A5178B6A965AACF3CD60B07A15061719';
$cipher = new AES();
$cipher->setKeyLength(256);
$cipher->setKey($key);
$res = $cipher->decrypt($data);
var_dump($res);
Security consideration:
If you're using only symmetric encryption you need the exact same key at the server and the client. If you send the encryption key from the server to the client or the other way around you need to encrypt your symmetric encryption key. The easiest way to do this would be to use TLS. If you use TLS, then the data as well as key are encrypted, so you don't need to encrypt it yourself. This doesn't provide any security, just a little bit of obfuscation. You should read: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/
Related
Hi there StackOverflow community,
After researching for countless of hours, I'm unable to find an explanation as to why my ouputs differ between javascript and my laravel application.
I could use input type hidden to make a post from my web browser, but that would defeat the purpose of having a secure client side processing and I fear that if I don't find the reason as to why this is happening, then decryption (which I plan to do through php) would not work either.
my php code is as follows:
$payload = "this is my plaintext";
$binary_signature = "";
$private_key = openssl_pkey_get_private(file_get_contents(storage_path('privatekey.pem')), 'enc123456789');
openssl_sign($payload, $binary_signature, $private_key, OPENSSL_ALGO_SHA256);
$signature = base64_encode($binary_signature);
$new_payload = $payload."&sign=".$signature; // where my actual plaintext is also used in my javascript code
$key = "thisismykey";
$iv = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0";
$encryption = openssl_encrypt($new_payload, 'AES-256-CBC', $key,OPENSSL_RAW_DATA, $iv);
dd(base64_encode($encyrption));
which outputs the following:
AEyHK+4DQWYjw8GeVV3mfzUJtk7ylxZINeryAdFptEbDyKOVbmNg8z32J2JgxGpFsQKpXxWaqDLf0IPNIq1jof0rKWhhDpaWzvTd0Tq/zgze7oGtZzEIqtdRDqax3ZvPkzNfuO/O14iW/YTwFkm9FLy9kGIirZDUTuAcOIjXGCgxhrhZHLn+V6SZpW5dYnH8u5rPDCeez2/HkUPI71YjD6hZ0DRjIkiXCyjPYH4fjNykz4yXo8hD+489Zxm8QPq1O1dyjR9JXSdrlYMWdixt6w0vz8EtPC8gZ+bDP/N/UEK07M52VB693zYb5uD1u7WuUUtsOjkr5ocF6QbEW7sjzI4q9yAxqvxRW/bkKqodcVqtglW6YsdJjrTR0EfA/Or/QF3e3QWVM5/2g4rT3ccE17OP6Rp/46yTpW9lOgS6Qiz2hY95GoaxbLfHB/Vb0Es+UppwDu8bd/u2Qax5erBi5ObZu3AjKNpTem45paspsKH3/vc2Jc810XrVQPjnDdZ8VrXvCgPiulywn5Mj28O7uUQ5bay3Zxy3bmHb7ESDEVMKiSEoru3LzDJ7wwPlidJzPcfWtuiMEMsPOv1Y6LaxtlizWM5/zYJFX/RA4d+KBl+Rn6BoPZDcX/6eh3oUoNhy
My JS Code (the plaintext is received through an ajax call which has the same sign method as you see from the php code, the encryption plaintext is of the same value from my php code)
function encrypt(plaintext, secretkey) {
var randomSeed = "";
randomSeed = secretkey;
var key = CryptoJS.enc.Utf8.parse(randomSeed.toUpperCase());
var iv = CryptoJS.enc.Utf8.parse("0000000000000000");
var encrypt = {};
encrypt = CryptoJS.AES.encrypt(plaintext, key, {
mode : CryptoJS.mode.CBC,
iv : iv
});
console.log("encryption is "+encrypt.toString());
return encrypt.toString(encrypt.toString());
}
Returns the correct value which is:
jLmAUr+JyCjbpctU4z6+dlF61jbHRphwTS0iAk3IRiy3jkfCtaCSWdiIO0awuX6G1jAlZroTiAuMl9OW0zj0q4HitndfGFtFUoMMCqZTzvMr6cy1TyG9EFz20T6ByrBnOvGuoVjv3Flufuk2Ghz5in2W2A3T+wF+SPXX/bIAnHtE3uW0bPl2q5tn6KyUI1uoQaYcMZKRPyzAQS7WSSwSOmAcVrRuDANgZQuO+3mh86QAdeFaYqFdZUnxD4c2kkbkGy17SUFfSK8Qjv+8tkTcYXV9QRRdWjGZiQQeyAr3PDKA4SDVzrcMNwJjTaLJiZv0Iau66HGpbf2yvRDLtIOoXQmnhs6NKTZpcSwZ07hHqVvBZmNRq+jqZOGw1s8GRH+Bz4yxSRycTS0DEddhyMoxhZcUc5wt42vDOYIEH2nuw/uu4gjrwpx0rVO1ssoZYRxvBaA6zSC4N04Wdn4JE2/LtXertDLEdLBtmk3c3n4QDU0tK5v31HMY7P7+fdQXU62niVxCNPSt9dpYa82IUrQuigNXgrbphQvZNmmcONi/4pnxJjKcKYpCn/1KhkBVUAhYm6UKJJvMNAo0M+cfsvReImrJx6IzPRdzTTFAQF5kW2NFkV4EIb0DtCF679RtdAhg5ShaP7QhqYL6EgFCs9WnJTACC26TmV20DAqUiuIYULLtjDW4qFOWi/y8D1JOWTar
I don't understand why my PHP encryption is giving the wrong output while my JavaScript encryption is giving the correct output
I'm hoping someone could give me an insight as to what I'm doing wrong from my PHP side. Wha I'm hoping to achieve is that my PHP encryption will output the same result as my JavaScript encryption.
Thank you in advance :)
I have solved my issue.
To those having a similar issue, here's a brief explanation. Crypto JS uses the following:
var key = CryptoJS.enc.Utf8.parse(randomSeed.toUpperCase());
var iv = CryptoJS.enc.Utf8.parse("0000000000000000");
Which translates to a word array if you console log the output. PHP needs to have the similar word array value that cryptoJS produces for it's AES encryption method. To solve this, you have to convert your $key and iv to be in hex format and format your code in php such as:
$key = pack("H*", "4a424d56595753555047553830334d42505a314f414256414c5a565239324659");
$iv = pack("H*", "30303030303030303030303030303030");
Then when you proceed to using openssl_encrypt
$encrypted_data = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
you will get the same output as crpytoJS.
Hope this helps.
I have this code in PHP (can't modify)
<?php
$myPlain = "123456789012345678900000";
$myKey = md5($myPlain, true);
$myKey .= substr($myKey, 0,8);
$encrypted = openssl_encrypt($myPlain, 'des-ede3', $myKey, OPENSSL_RAW_DATA);
print(base64_encode($encrypted));
This code returns
FTYDrZTZMjVBv5Fk/xcfFxJASaizzrmoPts7fGDvWjc=
When I try to replicate this in NodeJS
function testEde3(myKey, myPlain) {
try {
let md5Key = crypto.createHash('md5').update(myKey, 'utf-8').digest("base64").substr(0, 24);
console.log(md5Key); //outputs 4o1aJrSWN3bSfjuIX6VXgA==
console.log(md5Key.length); //outputs 24
const cipher = crypto.createCipheriv('des-ede3', md5Key, null);
let encrypted = cipher.update(myPlain, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
} catch ( ex ) {
return ex;
}
}
const myKey = "123456789012345678900000";
const myPlain = "123456789012345678900000";
const hash = testEd3(myKey, myPlain);
console.log(`Hash is: ${hash}`);
The output is
Hash is: lDQX9OGsopKOt6P9WQwekGsKDQGFpfGW50zbs3HrOfQ=
I'm thinking the problem is on MD5. If I try to encrypt without md5, the results are the same.
Thanks
The key in Php code consists of the 16 bytes of the MD5 hash, to which the first 8 bytes of the MD5 hash are appended, resulting in a 24 bytes key (as required for 3DES). This is currently not implemented in the NodeJS code, but can be achieved e.g. by:
let md5Key = crypto.createHash('md5').update(myKey, 'utf-8').digest();
md5Key = Buffer.concat([md5Key, md5Key.slice(0, 8)]);
With this change, the NodeJS code generates the ciphertext of the PHP code with the same input data.
des-ede3 means 3DES in ECB mode. Note that 3DES is outdated and slow and should be replaced by AES. ECB mode is generally insecure. Encrypting the key also makes little sense (but may only be for testing purposes).
I'm receiving an encrypted message from an external party. They're using php and mcrypt for encryption with the following configuration
algo: rijndael-256
mode: ecb
example encrypted message: "a364cb3bb55c2788b25f04ef6867d770771a7d0fdd44462b40233ea76a8bd00d". Its original message is "thank you"
The following images showing the configuration
From my side, I'm using nodejs to decrypt. I have a working version with node-mcrypt binding. But I want to avoid native modules so I'm looking for a pure javascript solution.
I tried node's crypto but its aes-256-ecb produces different (unreadable) output
The working code with MCrypt binding in nodejs:
const decryptAES256 = (encrypted: string, password: string): string => {
try {
const desEcb = new MCrypt('rijndael-256', 'ecb');
desEcb.open(md5(password));
const ciphertext = desEcb.decrypt(new Buffer(encrypted, 'hex'));
const plain = ciphertext.toString();
const isUTF8 = plain.split('').every(c => c.charCodeAt(0) <= 256);
if (!isUTF8) {
throw new Error('Invalid Input');
}
const unpadding = plain
.split('')
.filter(c => c.charCodeAt(0))
.join('');
return unpadding;
} catch (ex) {
console.error('Invalid token');
}
};
When you state "rijndael-256" that maybe specifying a 256-bit block size which is not AES. AES has one block size: 128-bits.
This seems to be born out by the encrypted output which is 32-binary bytes and for an input of "thank you" the output should be one block so it seems the block size is 32-bytes (256-bits).
Do not use mcrypt, it will just cause interoperability problems.
Make sure you are using AES which can be rijndael with a 128-bit block size.
Do not confuse the key size with the block size.
If the input data is not always a multiple of the block size then padding must be added to the input data], specify padding, PKCS#7 (née PKCS#5) padding which may be the default. mcrypt does not support standard padding. If you must interoperate with mcrypt you will need to specify no padding and perform the padding yourself.
After realizing that rijndael 256 is not equivalent to aes 256 (with 128 version is), I opt to find a rijndael specific lib in pure javascript and this is a working code:
const Rijndael = require('rijndael-js');
describe('cipher', () => {
it('should work', () => {
const text = 'thank you';
// + String.fromCharCode(0).repeat(5)
const key = '94a08da1fecbb6e8b46990538c7b50b2';
const cipher = new Rijndael(key, 'ecb');
const ciphertext = cipher.encrypt(text, 256);
expect(ciphertext.toString('hex')).toBe(
'a364cb3bb55c2788b25f04ef6867d770771a7d0fdd44462b40233ea76a8bd00d'
);
const plaintext = cipher.decrypt(ciphertext, 256);
const unpadded = plaintext.toString().replace(/\u0000*$/g, '');
expect(unpadded).toBe(text);
});
});
I'm having an issue encrypting my string in C++ and then decrypting in PHP. On the C++ side, I think everything is going fine. Below is my code for the C++ side.
unsigned char inbuffer[1024];
unsigned char outbuffer[1024];
unsigned char oneKey[] = "abc";
AES_KEY key;
AES_set_encrypt_key(oneKey, 128, &key);
string straa("hello world\n");
memcpy((char*)inbuffer, straa.c_str(), 13);
AES_encrypt(inbuffer, encryptedbuffer, &key);
LPCSTR pszSource = (LPCSTR)encryptedbuffer;
DWORD nDestinationSize;
if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, nullptr, &nDestinationSize))
{
LPTSTR pszDestination = static_cast<LPTSTR> (HeapAlloc(GetProcessHeap(), HEAP_NO_SERIALIZE, nDestinationSize * sizeof(TCHAR)));
if (pszDestination)
{
if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, pszDestination, &nDestinationSize))
{
printf("OUT: %s", pszDestination); // Base64 encoded output of encrypted string
}
}
}
This is my PHP code:
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
$out = openssl_decrypt(base64_decode("G6g0f/K7EzAw8fxn9BTFzw=="), 'AES-256-CBC', "abc", OPENSSL_RAW_DATA, $iv);
echo $out;
There is no output from the PHP code.
The C++ code would output the following:
OUT: G6g0f/K7EzAw8fxn9BTFzw==
CBC mode, the mode used in the PHP code, does require an iv and it must be the same as the one used for encryption, also the modes must be the same for both encryption and decryption. For CBC mode you need to supply a block sized iv (16-bytes for AES). The encryption key also should to be the correct size.
The iv is not explicitly set in the C++ code and the mode and padding use the default, it is always better to expel;icitly specify all parameters. The iv should be random for each encryption.
You might consider RNCryptor, it is multi language and platform and handles all the details.
I'm trying to obtain the same encryption results (using AES 256) between PHP/mySQL and Swift.
Here is the text i'm trying to encrypt : {"email":"aze#aze.com","password":"aze"}
Here is the key : toto
I'm using the SHA1 hash of the key to encrypt : 0B9C2625DC21EF05F6AD4DDF47C5F203837AA32C
Here is my PHP code (the result is what I expect, I use a local db to perform the encryption)
$data = array();
$data['email'] = 'aze#aze.com';
$data['password'] = 'aze';
$json = json_encode($data);
$request = $db->prepare("select AES_ENCRYPT('$json', SHA1('toto')) as data from dual");
$request->execute();
$request->setFetchMode(PDO::FETCH_ASSOC);
$encodedResult = $request->fetchAll();
$encodedResult = $encodedResult[0]['data'];
$base64Result = base64_encode($encodedResult));
Encoded result is ¤]¼–áú£?îfÞð"2Á«¯ä%s7Ûš>½qé}‘(J µƒ–"³}vÃë
Base64 result is pF28A5bh+qOdP+5mHN7wIjLBBKutr+Qlczfbmj69cel9kRYoShcgtYOWIrN9dsPr
How can I obtain the same result in Swift or Objective-C ? I tried different libraries such as CryptoSwift / CocoaSecurity, but the result is always different.
It seems that MySQL uses 0 padding, which I can't get to work on iOS.
Edit : To be clear I need to implement 0 padding on iOS side to obtain the same result as MySQL, and not PKCS7 on PHP/MySQL side.
With CryptoSwift you can easily apply custom padding
public struct ZeroPadding: Padding {
func add(data: [UInt8], blockSize:Int) -> [UInt8] {
// Padding logic here
}
func remove(data: [UInt8], blockSize:Int?) -> [UInt8] {
// Padding logic here
}
}
and pass it as parameter to encrypt()
let encrypted = AES(key: key, iv: iv, blockMode: .CBC)?.encrypt(message, padding: ZeroPadding())