I want to decode a BASE64 to String with ciphertext, key, and iv using Crypto-JS. I get the error Malformed UTF-8 data.
My code:
const CryptoJS = require('crypto-js')
const fs = require('fs');
// BASE64
const str = fs.readFileSync('file.txt','utf8')
const genRanHex = function(_0x8d0344) {
for (var _0x15f7b3 = [], _0x2491b5 = '0123456789abcdef', _0x2b0a63 = 0x0; _0x2b0a63 < _0x8d0344; _0x2b0a63++) _0x15f7b3['push'](_0x2491b5['charAt'](Math['floor'](Math['random']() * _0x2491b5['length'])));
return _0x15f7b3['join']('');
}
var KEYS = genRanHex(0x10) + '3c07f4b0efef700a',
ciphertext = str['substring'](0x18),
key = CryptoJS['enc']['Hex']['parse'](KEYS),
iv = CryptoJS.enc.Base64.parse(str.substring(0x0, 0x18))
try {
const decrypted = CryptoJS.AES.decrypt(ciphertext, key, {iv }).toString(CryptoJS.enc.Utf8);
var originalText = JSON.parse(decrypted)
console.log(originalText)
} catch (err) {
console.error(err)
}
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'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'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);
I am using localStorage to store data and i want to encrypt the password, then when the password is encrypted in the localStorage i want now to decrypt it to be able to log-in. And i try the encryption is working but the decryption is not working and error message is:
Uncaught SyntaxError: Unexpected end of input
I am using CryptoJS v3.1.2
code.google.com/p/crypto-js
here the code:
var JsonFormatter = {
stringify: function (cipherParams) {
var jsonObj = {ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)};
if (cipherParams.iv) {jsonObj.iv = cipherParams.iv.toString();}
if (cipherParams.salt) {jsonObj.s = cipherParams.salt.toString();}
return JSON.stringify(jsonObj);
},
parse: function (jsonStr) {
var jsonObj = JSON.parse(jsonStr);
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
if (jsonObj.iv) {cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv)}
if (jsonObj.s) {cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s)}
return cipherParams;
}
};
encryption.js
function btnSubmit(){
var p = document.getElementById("setpass").value;
if(p.length >= 5){
var password = localStorage["Password"];
var encoded = CryptoJS.AES.encrypt(JSON.stringify(p), password, {format: JsonFormatter}).ciphertext.toString();
localStorage.setItem("Password", encoded);
jAlert('Password is set', 'URIBlocker');
window.location.reload();
}
else
{
//Notification
}
}
decrypt.js
function login() {
var usepass = document.getElementById('usepass').value;
var password = localStorage["Password"];
var encrypted = localStorage.getItem("Password");
var decrypted = CryptoJS.AES.decrypt(encrypted, password, {formatter: JsonFormatter}).toString();
var secret = JSON.parse(decrypted);
if (usepass === secret)
{
$('.bd_class').show();
$('.go_class').hide();
}
else
{
$('.bd_class').hide();
$('go_class').show();
}
}
Something is wrong and i don't know the error is Uncaught SyntaxError: Unexpected end of input