I'm trying for some time to decrypt a message in AES that use a Java app , but it never works . Can someone help me?
var options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 };
/*** encrypt */
var json = CryptoJS.AES.encrypt("Message", "KEY", options);
var ciphertext = json.ciphertext.toString(CryptoJS.enc.Base64);
console.log("chiper text ", ciphertext);
/*** decrypt */
var decrypted = CryptoJS.AES.decrypt(json, "KEY", options);
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);
console.log("decrypted ", plaintext);
But it is always generated a different ciphertext, never the same from my database.
var CryptoJS = require("crypto-js");
var key = CryptoJS.enc.Utf8.parse('b75524255a7f54d2726a951bb39204df');
var iv = CryptoJS.enc.Utf8.parse('1583288699248111');
var text = "My Name Is Nghĩa";
var encryptedCP = CryptoJS.AES.encrypt(text, key, { iv: iv });
var decryptedWA = CryptoJS.AES.decrypt(encryptedCP, key, { iv: iv});
var cryptText = encryptedCP.toString();
console.log(cryptText);
console.log(decryptedWA.toString(CryptoJS.enc.Utf8));
//Decode from text
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(cryptText )
});
var decryptedFromText = CryptoJS.AES.decrypt(cipherParams, key, { iv: iv});
console.log(decryptedFromText.toString(CryptoJS.enc.Utf8));
try this to encrypt data
var data = CryptoJS.AES.encrypt(message, key);
data = data.toString()
then decrypt it like this
var decr = CryptoJS.AES.decrypt(data, key);
decr = decr.toString(CryptoJS.enc.Utf8);
Related
const crypto = require('crypto')
class encryptedDataClass {
constructor(massage){
this.algorithm = 'aes-256-cbc'
this.initVector = crypto.randomBytes(16);
this.massage = massage;
this.Securitykey = crypto.randomBytes(32);
}
encrypted(){
const cipher = crypto.createCipheriv(this.algorithm, this.Securitykey, this.initVector);
let encryptedData = cipher.update(this.massage, "utf-8", "hex");
return encryptedData += cipher.final("hex");
}
decrypted(){
const decipher = crypto.createDecipheriv(this.algorithm, this.Securitykey,
this.initVector);
let decryptedData = decipher.update(this.massage, "hex", "utf-8");
return decryptedData += decipher.final("utf-8");
}
}
const secureName = new
encryptedDataClass("850749d212e39c8e24aee37bbb43e3c1eaee69ea592eeaeb93da5c83437f64a0")
console.log(secureName.decrypted())
I created that key using encrypted function but I can't decode that key, I'm getting an error:
06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
How can I fix this error?
As AKX mentioned, you're creating a new IV everytime and when decrypting, you need the original IV. See my solution below. I'm storing the IV and later retrieving it by splitting the string on the "."
const crypto = require("crypto");
const algorithm = "aes-192-cbc"; // algorithm to use
const password = 'defineaPassword';
const key = crypto.scryptSync(password, 'salt', 24); // create key
const iv = crypto.randomBytes(16); // generate different ciphertext everytime
module.exports = {
encryptAndBase64 (messagetext) {
try {
const iv = crypto.randomBytes(16); // generate different ciphertext everytime
const cipher = crypto.createCipheriv(algorithm, key, iv);
const ciphertext = cipher.update(messagetext, 'utf8', 'hex') + cipher.final('hex'); // encrypted text
return `${iv.toString('base64')}.${ciphertext}`;
} catch (e) {
console.log(`error while encrypting: ${e.message}`);
return messagetext;
}
},
decrypt (messagetext) {
const split = messagetext.split('.');
const iv = split[0];
messagetext = split[1];
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'base64'));
return decipher.update(messagetext, 'hex', 'utf8') + decipher.final('utf8'); // deciphered text
},
};
I am trying to replicate Javascript CryptoJS v3.1.2 AES.encrypt in C#. I have tried AesManaged, RijndaelManaged but not able to replicate same output in C# as javascript produces.
The java script code is as below:
var enteredText = "123456";
var _0x6722=["\x75\x37\x47\x75\x35\x70\x6F\x73\x76\x77\x44\x73\x58\x55\x6E\x56\x35\x5A\x61\x71\x34\x67\x3D\x3D","\x70\x61\x72\x73\x65","\x42\x61\x73\x65\x36\x34","\x65\x6E\x63"];
var rkEncryptionKey=CryptoJS[_0x6722[3]][_0x6722[2]][_0x6722[1]](_0x6722[0])
var _0x283e=["\x35\x44\x39\x72\x39\x5A\x56\x7A\x45\x59\x59\x67\x68\x61\x39\x33\x30\x61\x55\x4B\x32\x77\x3D\x3D","\x70\x61\x72\x73\x65","\x42\x61\x73\x65\x36\x34","\x65\x6E\x63"];
var rkEncryptionIv=CryptoJS[_0x283e[3]][_0x283e[2]][_0x283e[1]](_0x283e[0])
var utf8Stringified = CryptoJS.enc.Utf8.parse(enteredText);
var encrypted = CryptoJS.AES.encrypt(utf8Stringified.toString(), rkEncryptionKey,
{
mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv
});
var encryptedText = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
This will produce jvYWNkANUAkYOSEbuJxv1w== as output in javascript.
Below is my C# code which I have written for the AES:
string result = "";
try
{
byte[] keybyte = Convert.FromBase64String("u7Gu5posvwDsXUnV5Zaq4g==");
byte[] keyiv = Convert.FromBase64String("5D9r9ZVzEYYgha930aUK2w==");
byte[] bytes = Encoding.UTF8.GetBytes("123456");
AesManaged aesManaged = new AesManaged();
aesManaged.KeySize = 128;
aesManaged.Key = keybyte;
aesManaged.BlockSize = 128;
aesManaged.Mode = CipherMode.ECB;
aesManaged.Padding = PaddingMode.PKCS7;
aesManaged.IV = keyiv;
AesManaged aesManaged2 = aesManaged;
string text;
using (ICryptoTransform cryptoTransform = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
{
text = Convert.ToBase64String(cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length));
}
result = text;
}
catch { }
My C# code is not producing the same output. Please suggest what issue I have in my C#
I have the following encryption method which uses CryptoJS to encrypt a password.
function encrypt() {
var val = document.getElementById('password').value;
var key = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');
var ivec = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
var dataString = CryptoJS.enc.Utf8.parse(val);
var encrypted = CryptoJS.AES.encrypt(dataString.toString(), key,
{ mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: ivec });
document.dform.plaintext.value = encrypted.toString();
form.submit();
}
The following decrypt method doesn't give me the desired result:
function decrypt() {
var val = document.getElementById('password').value;
var key = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');
var ivec = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
//var dataString = CryptoJS.enc.Utf8.parse(val);
var decrypted = CryptoJS.AES.decrypt(val, key,
{ mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: ivec });
document.dform.plaintext.value = decrypted.toString();
//form.submit();
}
Sample Ciphertext: y5uoJYFk1+QS2I4Wx7QnsBq8dGe30ucBNaXsTnNhTOE=
Plaintext: helloworld
I'm encrypting some parameters in PHP using
openssl("parameter", "AES-256-ECB", "client")
and I wish to decrypt in CryptoJS:
CryptoJS.AES.decrypt(parameter, "client", {mode: CryptoJS.mode.ECB}).toString(CryptoJS.enc.Utf8);
but it's throwing an empty string.
Any suggestions?
CryptoJS: PHP openssl encrypt -> javascript decrypt
PHP:
function CryptoJSAesEncrypt($passphrase, $plain_text){
$salt = openssl_random_pseudo_bytes(256);
$iv = openssl_random_pseudo_bytes(16);
//on PHP7 can use random_bytes() istead openssl_random_pseudo_bytes()
//or PHP5x see : https://github.com/paragonie/random_compat
$iterations = 999;
$key = hash_pbkdf2("sha512", $passphrase, $salt, $iterations, 64);
$encrypted_data = openssl_encrypt($plain_text, 'aes-256-cbc', hex2bin($key), OPENSSL_RAW_DATA, $iv);
$data = array("ciphertext" => base64_encode($encrypted_data), "iv" => bin2hex($iv), "salt" => bin2hex($salt));
return json_encode($data);
}
$string_json_fromPHP = CryptoJSAesEncrypt("your passphrase", "your plain text");
JS:
function CryptoJSAesDecrypt(passphrase,encrypted_json_string){
var obj_json = JSON.parse(encrypted_json_string);
var encrypted = obj_json.ciphertext;
var salt = CryptoJS.enc.Hex.parse(obj_json.salt);
var iv = CryptoJS.enc.Hex.parse(obj_json.iv);
var key = CryptoJS.PBKDF2(passphrase, salt, { hasher: CryptoJS.algo.SHA512, keySize: 64/8, iterations: 999});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv});
return decrypted.toString(CryptoJS.enc.Utf8);
}
console.log(CryptoJSAesDecrypt('your passphrase','<?php echo $string_json_fromPHP?>'));
CryptoJS: javascript encrypt -> PHP openssl decrypt
JS:
function CryptoJSAesEncrypt(passphrase, plain_text){
var salt = CryptoJS.lib.WordArray.random(256);
var iv = CryptoJS.lib.WordArray.random(16);
//for more random entropy can use : https://github.com/wwwtyro/cryptico/blob/master/random.js instead CryptoJS random() or another js PRNG
var key = CryptoJS.PBKDF2(passphrase, salt, { hasher: CryptoJS.algo.SHA512, keySize: 64/8, iterations: 999 });
var encrypted = CryptoJS.AES.encrypt(plain_text, key, {iv: iv});
var data = {
ciphertext : CryptoJS.enc.Base64.stringify(encrypted.ciphertext),
salt : CryptoJS.enc.Hex.stringify(salt),
iv : CryptoJS.enc.Hex.stringify(iv)
}
return JSON.stringify(data);
}
PHP:
function CryptoJSAesDecrypt($passphrase, $jsonString){
$jsondata = json_decode($jsonString, true);
try {
$salt = hex2bin($jsondata["salt"]);
$iv = hex2bin($jsondata["iv"]);
} catch(Exception $e) { return null; }
$ciphertext = base64_decode($jsondata["ciphertext"]);
$iterations = 999; //same as js encrypting
$key = hash_pbkdf2("sha512", $passphrase, $salt, $iterations, 64);
$decrypted= openssl_decrypt($ciphertext , 'aes-256-cbc', hex2bin($key), OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
in mi tests I have used : github.com/sytelus/CryptoJS
PHP Encryption
function encryptPhp($string) {
$encrypt_method="AES-256-CBC";
$secret_key='secret_key';
$secret_iv='secret_iv';
$key=hash('sha256',$secret_key);
$iv=substr(hash('sha256',$secret_iv),0,16);
$output=openssl_encrypt($string,$encrypt_method,$key,0,$iv);
$output=base64_encode($output);
return $output
}
javascript Equialent
function decryptString($string) {
var Utf8 = CryptoJS.enc.Utf8;
const $secret_key='secret_key';
const $secret_iv='secret_iv';
const key= CryptoJS.SHA256($secret_key).toString(CryptoJS.enc.Hex).substring(0,32);
let iv= CryptoJS.SHA256($secret_iv).toString(CryptoJS.enc.Hex).substring(0,16);
const encrypt = CryptoJS.enc.Base64.parse($string).toString(CryptoJS.enc.Utf8);
const decrypt = CryptoJS.AES.decrypt(encrypt, Utf8.parse(key), { iv: Utf8.parse(iv)}).toString(Utf8);
return decrypt;
}
Also Don't use secret key & secret iv in browser side, it may affect security
Please use this method It's work for me.. Thanks
Typescript Code (Anuglar 4+) :
encryptUsingAES256() {
let _key = CryptoJS.enc.Utf8.parse(your_token_here);
let _iv = CryptoJS.enc.Utf8.parse(your_token_here);
let encrypted = CryptoJS.AES.encrypt(
this.request, _key, {
keySize: 16,
iv: _iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
this.encrypted = encrypted.toString();
console.log(this.encrypted)
}
decryptUsingAES256() {
let _key = CryptoJS.enc.Utf8.parse(your_token_here);
let _iv = CryptoJS.enc.Utf8.parse(your_token_here);
this.decrypted = CryptoJS.AES.decrypt(
this.encrypted, _key, {
keySize: 16,
iv: _iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
console.log(this.decrypted)
}
I need to create an encryption and decryption function in my NodeJS application. Can anyone help and point me in the right direction?
After a bit of digging, I was able to answer my own question... Sorry for the lack of clarity and detail. Will work on that for the next question.
I've included the functions to encrypt and decrypt, and the "helping" functions to generate a key and generate the initialization vector as well.
var crypto = require('crypto');
var encrypt = function encrypt(input, password) {
var key = generateKey(password);
var initializationVector = generateInitializationVector(password);
var data = new Buffer(input.toString(), 'utf8').toString('binary');
var cipher = crypto.createCipheriv('aes-256-cbc', key, initializationVector.slice(0,16));
var encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
var encoded = new Buffer(encrypted, 'binary').toString('base64');
return encoded;
};
var decrypt = function decrypt(input, password) {
var key = generateKey(password);
var initializationVector = generateInitializationVector(password);
var input = input.replace(/\-/g, '+').replace(/_/g, '/');
var edata = new Buffer(input, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-256-cbc', key, initializationVector.slice(0,16));
var decrypted = decipher.update(edata, 'hex', 'utf8');
decrypted += decipher.final('utf8');
var decoded = new Buffer(decrypted, 'binary').toString('utf8');
return decoded;
};
var generateKey = function generateKey(password) {
var cryptographicHash = crypto.createHash('md5');
cryptographicHash.update(password);
key = cryptographicHash.digest('hex');
return key;
}
var generateInitializationVector = function generateInitializationVector(password) {
var cryptographicHash = crypto.createHash('md5');
cryptographicHash.update(password + key);
initializationVector = cryptographicHash.digest('hex');
return initializationVector;
}
var password = 'MyPassword';
var originalStr = 'hello world!';
var encryptedStr = encrypt(originalStr, password);
var decryptedStr = decrypt(encryptedStr, password);
Hats off to adviner for the inspiration of the solution.
His post can be here: here
I had originally gotten this working with this post by dave, but that didn't work for input values with a character length greater than 15. The updated code above works for inputs of any length.