var token = "WMwiDeJrawUKHif7D5a8yd4ne6Mv";
var salt = "ERtrg56hfg5";
var key = CryptoJS.enc.Hex.parse('B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF');
var iv = CryptoJS.enc.Hex.parse('7E892875A52C59A3B588306B13C31FBD');
var encrypted = CryptoJS.AES.encrypt(token, key, { iv: iv });
context.setVariable("encryptedtoken", encrypted);
but it is not setting to variable saying it is an object.
what I need to do
I think you have to use encrypted.ciphertext
var encrypted = CryptoJS.AES.encrypt(token, key, { iv: iv });
context.setVariable("encryptedtoken", encrypted.ciphertext);
From CryptoJS documentation:
The ciphertext you get back after encryption isn't a string yet. It's a CipherParams object. A CipherParams object gives you access to all the parameters used during encryption. When you use a CipherParams object in a string context, it's automatically converted to a string according to a format strategy. The default is an OpenSSL-compatible format.
<script>
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
alert(encrypted.key); // 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223
alert(encrypted.iv); // 7781157e2629b094f0e3dd48c4d786115
alert(encrypted.salt); // 7a25f9132ec6a8b34
alert(encrypted.ciphertext); // 73e54154a15d1beeb509d9e12f1e462a0
alert(encrypted); // U2FsdGVkX1+iX5Ey7GqLND5UFUoV0b7rUJ2eEvHkYqA=
</script>
Related
I have trouble decrypting data in CryptoJS. After decrypting the data it returns an empty string
Here is my code:
Javascript code
var iv = CryptoJS.enc.Utf8.parse(dataa[5]);
var key = 'AAAAAAAAAAAAAAAA';
key = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.AES.decrypt(dataa[1], key, { iv: iv, mode: CryptoJS.mode.CBC});
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
console.log(decrypted);
alert(decrypted);
The alert returns an empty string. Dataa[5] is the IV and dataa1 is the data that has to decrypted.
After the CryptoJS.AES.decrypt the variable decrypted is already empty.
I am new to CryptoJS and do not understand why it wont work.
dataa[ 1 ] = gXodEwQf2Mk+ZW9RDiktNw
dataa[ 5 ] = s/D0LaJK1SwL9pgF/r1DAQ==
I am encrypting a text with AES256 in swift language and outputting it as hex. I want to decrypt this code I received with JS, but I could not reach the result. I tried the CryptoJS library but still couldn't get the result I wanted. All I want is the js code that will give me the decoded version when I enter the IV, password and ciphertext.
const crypto = require("crypto");
var key = "";
const iv = "";
const token = "";
function decrypt(token, iv, key) {
const decrypter = crypto.createDecipheriv("aes-256-cbc", key, iv);
let decrypted = decrypter.update(token, "hex", "utf8");
decrypted += decrypter.final("utf8");
return decrypted
}
console.log(decrypt(token, iv, key));
With the Node.js code above, I achieve what I want, but I want to do it with normal JS code, not using node. I don't want to mess with the server. I would be very happy if you help.
EDIT:
I am using CryptoSwift library in Swift language.
func encryption(uuid: String, token: String) -> String {
do {
let aes = try AES(key: String(uuid.prefix(32)), iv: String(uuid.prefix(16)))
let ciphertext = try aes.encrypt(Array(token.utf8))
let encrypttext = ciphertext.toHexString()
return encrypttext
}
catch {
return "error"
}
}
I tried to do something with CryptoJS with the codes from the site below, but it didn't work like the codes in Node.js.
https://embed.plnkr.co/0VPU1zmmWC5wmTKPKnhg/
EDIT2:
I've been trying different things but couldn't quite figure it out. I get an error when I add PBKDF2. I don't fully understand the problem.
var password = "6268890F-9B58-484C-8CDC-34F9C6A9";
var iv = "6268890F-9B58-48";
var cipher = "79a247e48ac27ed33ca3f1919067fa64";
/*
var key = CryptoJS.PBKDF2(password, {
keySize: 32
});
*/
var dec= CryptoJS.enc.Hex.parse(cipher);
const decrypted = CryptoJS.AES.decrypt({
ciphertext: dec
},
password, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log(decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/pbkdf2.js"></script>
CryptoJS uses WordArrays, so that key, IV and ciphertext have to be converted accordingly. For this purpose the appropriate encoders have to be applied. Furthermore decrypt() expects the ciphertext as CipherParams object.
This results in the following possible CryptoJS implementation:
var ciphertext = "79a247e48ac27ed33ca3f1919067fa64";
var key = "6268890F-9B58-484C-8CDC-34F9C6A9";
var iv = "6268890F-9B58-48";
var ciphertextWA = CryptoJS.enc.Hex.parse(ciphertext);
var keyWA = CryptoJS.enc.Utf8.parse(key);
var ivWA = CryptoJS.enc.Utf8.parse(iv);
var ciphertextCP = { ciphertext: ciphertextWA };
var decrypted = CryptoJS.AES.decrypt(
ciphertextCP,
keyWA,
{ iv: ivWA }
);
console.log(decrypted.toString(CryptoJS.enc.Utf8)); // Apple
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
which is functionally identical to the posted NodeJS code that also successfully decrypts the test data.
Regarding the question asked in the comment about the encodings:
In general, the decryption side must have knowledge of the encodings used for encryption. However, in this case the encodings can be derived from the posted NodeJS code:
For decryption, the input encoding of the ciphertext is specified as 'hex', see decipher.update().
key and iv are defined as strings which are UTF-8 encoded, see crypto.createDecipheriv().
Also, the data used is consistent with these conclusions.
Note that for security reasons a static IV may not be used. Instead, a random IV must be generated for each encryption.
Also, no password may be applied as key, even if it has the right length. If a password is to be used, a key derivation is necessary, e.g. with PBKDF2.
For test purposes, the data is of course enough.
I am new to encryption. What I am trying to do is decrypt a cipher text using javascript library, CryptoJS. This code example works fine. The encryption part returns ciphertext "ae06b481cecfa67c98c125" (which is right) while decrypting the same object returns the original string "Hello World".
var key = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var iv = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var encrypted = CryptoJS.AES.encrypt("Hello World", key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
alert(encrypted.ciphertext);
var decryptedData = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
originalData = decryptedData.toString(CryptoJS.enc.Utf8);
alert(originalData);
Well this part works fine but when I try this chunk of code by passing the cipher text as a string independently, I don't get the decrypted message.
var key = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var iv = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var ciphertext = "ae06b481cecfa67c98c125";
// raw = CryptoJS.enc.Base64.parse(cipher);
var decryptedData = CryptoJS.AES.decrypt(ciphertext, key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
originalData = decryptedData.toString(CryptoJS.enc.Utf8);
alert(originalData);
console.log(originalData);
Can somebody please point out why?
I have the following libraries included in the html file.
<script src="js/rollups/aes.js"></script>
<script src="js/components/mode-ctr.js"></script>
<script src="js/components/pad-nopadding.js"></script>
CryptoJS.AES.decrypt expects either a CipherParams object or an OpenSSL-formatted string. If the passed key is a string then the OpenSSL-formatted string is expected and otherwise the CipherParams object.
Since your key is not a string, you need this:
var decryptedData = CryptoJS.AES.decrypt({
ciphertext: CryptoJS.enc.Hex.parse("ae06b481cecfa67c98c125")
}, key, {
iv: iv,
mode: CryptoJS.mode.CTR,
padding: CryptoJS.pad.NoPadding
});
If the key is a string, then it isn't actually a key, but assumed to be a password and a key will be derived from that password with a random 8 byte salt. This would be comparable to OpenSSL's EVP_BytesToKey function.
I have a file that I encrypt using AES. Historically, I've had a set of tools (Java, Python) each of which is capable to both encrypt and decrypt these files. However, I've been having problems decrypting these files using CryptoJS.
The encrypted file has IV stored in the first 16 bytes, the rest is payload. During encryption key is formed by using hashing the password string via SHA-1 and using first 32 characters from the hex digest. I've gotten to the point where I can confirm that both IV and key used by CryptoJS is byte-wise identical to the ones used by other tools yet AES.decrypt() produces a buffer that I can't convert back to text.
Here's the decryption code. content and iv are binary strings read directly from file. password is a string with textual password. The code fails trying to convert the result to UTF8 (which I assume is due to the fact that decryption did not succeed).
function string2bytes(s) {
var bytes = [];
for (var i = 0; i < s.length; i++) {
bytes.push(s.charCodeAt(i));
}
return bytes;
}
function decryptData(content, ivx, password) {
// build a key out of text password
var key = CryptoJS.SHA1(password).toString(CryptoJS.enc.Hex).substring(0, 32);
console.log("key0: ", key);
key = string2bytes(key)
console.log(key);
// Convert IV from binary string to WordArray
var iv = CryptoJS.enc.Latin1.parse(ivx);
console.log("IV: ", iv.toString(CryptoJS.enc.Hex));
var decrypted = CryptoJS.AES.decrypt(content, key, { iv: iv });
console.log("raw decrypted: ", decrypted);
console.log("decrypted: ", iv.toString(CryptoJS.enc.Latin1));
console.log("decrypted: ", iv.toString(CryptoJS.enc.Utf8));
}
Any help would be appreciated.
Found a solution by sticking to WordArrays (even for the arguments where a binary string is ostensibly OK): The following function does work. The arguments are as follows:
data is a base64 string with encrypted text
password is a regular string with password
iv is a base64 string with an IV.
so
function decryptData(data, password, iv) {
var data = CryptoJS.enc.Base64.parse(data);
var key = CryptoJS.SHA1(password).toString(CryptoJS.enc.Hex).substring(0, 32);
key = CryptoJS.enc.Base64.parse(btoa(key));
var iv = CryptoJS.enc.Base64.parse(iv);
var decrypted = CryptoJS.AES.decrypt({ciphertext: data}, key, {iv: iv});
return decrypted.toString(CryptoJS.enc.Utf8);
}
I am trying to Encrypt a string using AES 128bit encryption. I have code for both Javascript and C#. The main objective is to encrypt the string using Javascript CryptoJS and then take the resultant cipher text and Decrypt it using C# AES AesCryptoServiceProvider.
Javascript Code:
function EncryptText()
{
var text = document.getElementById('textbox').value;
var Key = CryptoJS.enc.Hex.parse("PSVJQRk9QTEpNVU1DWUZCRVFGV1VVT0=");
var IV = CryptoJS.enc.Hex.parse("YWlFLVEZZUFNaWl=");
var encryptedText = CryptoJS.AES.encrypt(text, Key, {iv: IV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
//var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
var encrypted = document.getElementById('encrypted');
encrypted.value = encryptedText;
}
C# Code:
private String AES_decrypt(string encrypted)
{
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Pkcs7;
aes.Key = Key;
aes.IV = IV;
ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] secret = crypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
crypto.Dispose();
return System.Text.ASCIIEncoding.ASCII.GetString(secret);
}
When using "hello" as the plain text for javascript i get this ciphertext:
uqhe5ya+mISuK4uc1WxxeQ==
When passing that into the C# application, upon running the Decrypt method i recieve:
Padding is invalid and cannot be removed.
I am stumped here and have tried many solutions resulting in the same error.
When encrypting hello through the C# encryption AES method I receive:
Y9nb8DrV73+rmmYRUcJiOg==
I thank you for your help in advance!
javascript code :
function EncryptText()
{
var text = CryptoJS.enc.Utf8.parse(document.getElementById('textbox').value);
var Key = CryptoJS.enc.Utf8.parse("PSVJQRk9QTEpNVU1DWUZCRVFGV1VVT0="); //secret key
var IV = CryptoJS.enc.Utf8.parse("2314345645678765"); //16 digit
var encryptedText = CryptoJS.AES.encrypt(text, Key, {keySize: 128 / 8,iv: IV, mode: CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7});
var encrypted = document.getElementById('encrypted');
encrypted.value = encryptedText;
//Pass encryptedText through service
}
C# code :
private String AES_decrypt(string encrypted,String secretKey,String initVec)
{
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
//aes.BlockSize = 128; Not Required
//aes.KeySize = 256; Not Required
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Pkcs7;
aes.Key = Encoding.UTF8.GetBytes(secretKey);PSVJQRk9QTEpNVU1DWUZCRVFGV1VVT0=
aes.IV = Encoding.UTF8.GetBytes(initVec); //2314345645678765
ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] secret = crypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
crypto.Dispose();
return System.Text.ASCIIEncoding.ASCII.GetString(secret);
}
Used above code working fine !!!
Try using var Key = CryptoJS.enc.Utf8.parse("PSVJQRk9QTEpNVU1DWUZCRVFGV1VVT0="); instead of HEX.
Because actually the string you are putting in your key (and IV) and parsing is not a hex string. hex is 0 to F.
First, your Key variable in JS contains a string with 32 characters (after the odd-looking parse call). Although this might be interpreted as a 128-bit key, there is a certain chance that CryptoJS takes it as a pass phrase instead (and generates a key from it using some algorithm). So your actual key looks quite different. The string also looks suspiciously like hex-encoded, so there might be some additional confusion about its C# value. You have to make sure that you are using the same key in JS and C#.
Second, the IV variable also, after parsing, looks like a hex-encoded value. So you have to be careful what value you are using on the C# side as well.
FYI, here are the values for Key and IV after parsing:
Key = 00000000000e00000d000c0000010000,
IV = 0000000e000f0a00
Thank you "Uwe" parsing with UTF8 solved everything.
What happens if you use: var Key = CryptoJS.enc.Utf8.parse("PSVJQRk9QTEpNVU1DWUZCRVFGV1VVT0="); instead >of HEX? And what is your Key and IV in C#? Because actually the string you are putting in your key and >parsing is not a hex string. hex is 0 to F
Thank you so much!