I am trying to decrypt the below message which has been encrypted using AES CTR 128(The encryption is done in PHP need to decrypt in Javascript).
const message = "DEnw6dO5nEZ4k532f3I8U6Vy1m/kgeqZhPAUqjVwCDwBRTUcxkgSn95ROXdy3lPF7ybbIiDIUYtmfru6AaNvUlP9HxOdlMkjSJDMDz7pcDj+Hqioipp/hqfSqPfSkFI8Q+VkBV9b2zNy9lamy4NmaFBo03KvVm3Hw2cMWHeRgE8DTJYPoYrBqIlKJ3PT7E3edd433UGRC/wdZ1jkf1cgpD3HdMHDDRtLnA2q/mbmuYHs7hZSz+CLzBHP6iq4+jEO/6FrLCQSPXqEwyRvTQ73ngS1KOoI5LdhQV7s7vrKJcxHWEBX5A84F7VRo+at/0aE0m71GwmHvJSs5ZrLCkuiLKHqyzO4SUHNeP0f1VqQmuphC0o8M912xfquBI9tv0TIipbvw2hNKKL66tYCBSx8W0C6rodJ+yirHs+Q5CorBqzrYr28it3gqs0bHrkN7A=="
const key = "AJ89HFJHAJ89HFJH"
const iv = "hsjsjdkdueooqpjj"
CryptoJS.AES.decrypt(message, key, { iv: iv, mode: CryptoJS.mode.CTR })
console.log("Here is decrypted",decrypted.toString(CryptoJS.enc.Utf8))
After this I am getting below error message in console
Below is the PHP code which has been used
$encryption_text = openssl_encrypt($text, $crypto_details['ciphering'], $crypto_details['cryptokey'], $crypto_details['option'], $crypto_details['iv']);
Checked multiple resources but not able to find correct solution for this please guide me.
Thanks.
Related
I am creating an app with reactnative and laravel,
so my code in laravel is creating a Qr code with a crypted data and send it to my front end (Reactjs),
When i try o decrypted in react native using Crypto js it adds a few caractere that i didn't add in my back end ,
I will show all function and exmeples ,
//Code in laravel crypt my QR info
$unix =time();
$unix_hashed = Crypt::encrypt($unix);
return QrCode::size(100)->generate($unix_hashed);
// Code in react native with cryptojs for the decrypt
var key = '6AhFLqwlExB9tn2Twql62EtbFDqBEv+S7tXW3h6a/0o=';
let encrypted = atob(data);
encrypted = JSON.parse(encrypted);
const iv = CryptoJS.enc.Base64.parse(encrypted.iv);
const value = encrypted.value;
key = CryptoJS.enc.Base64.parse(key);
var decrypted = CryptoJS.AES.decrypt(value, key, {
iv: iv
});
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
// exemple of the output in console :
this is my output
but the problem it should be like this :
i:1634986874;
the " " & i & : & ; is extra
Can some one help me
Thanks
Crypt::encrypt() uses AES-256 in CBC mode by default, s. here.
Before encryption, the plaintext is serialized by calling the PHP function serialize() generating a storable representation of the value. For instance, serialize(1635015182) returns i:1635015182; and serialize('Hello world') returns s:11: "Hello world";. In the serialized data, i denotes an integer, s:11 denotes an 11 character string.
If decryption is performed with Crypt::decrypt(), unserialize() is called after decryption, which deserializes the data and restores the original plaintext.
When decrypting with another library, such as CryptoJS, the deserialization is not performed, so the serialized plaintexts are returned. Therefore, deserialization must be done manually here.
Fortunately, there is the locutus library that provides ports of PHP functionalities to JavaScript, so unserialize() can also be executed under JavaScript/NodeJS without much effort:
var CryptoJS = require('crypto-js');
var atob = require('atob');
var unserialize = require('locutus/php/var/unserialize')
// ciphertext from Crypt::encrypt()
var data = "eyJpdiI6IkYyaDhxenFJM0FjaW56TW83NkpuNHc9PSIsInZhbHVlIjoiNzhSeUs5em1WblpaRWk2OVBWVURnUT09IiwibWFjIjoiODg1NGFkOTk0MGVjMjIxODAyNzExOTgxYjhiMDM4YjliMmM5NzE5Mjc0YzFmNDVlMWU1MWRkMTQ2N2Q5ODdmNCJ9"
var key = '6AhFLqwlExB9tn2Twql62EtbFDqBEv+S7tXW3h6a/0o=';
let encrypted = atob(data);
encrypted = JSON.parse(encrypted);
const iv = CryptoJS.enc.Base64.parse(encrypted.iv);
const value = encrypted.value;
key = CryptoJS.enc.Base64.parse(key);
var decrypted = CryptoJS.AES.decrypt(value, key, {
iv: iv
});
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
// unserialize
console.log(decrypted); // i:1635015182;
console.log(unserialize(decrypted)); // 1635015182
The unserialize() call in the last line restores the original plaintext.
Please note that encrypted.mac contains a MAC for checking data integrity. Here you can find a PHP implementation for Crypt::encrypt().
I have found a library about Elliptic Curve Cryptography in JavaScript. I have learned how to encrypt the message. But, I didn't find how to decrypt it to the original message.
The code for encryption:
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
var msg = "hello";
let myKey = ec.keyFromPrivate('29f3c33a550d3810e6b82b7b510672118aeabcf8b19e00172e4623cbf480d2b8');
const sig = myKey.sign(msg, 'base64');
var derSign = sig.toDER('hex');
console.log (derSign)
output:
3044022076e7fbf80454f764e346dd359eb7f2002802e68d30a689d77d6211aa2c6e9d7302201b5f35d92b8f4aefd5f69d9d21e3dfba75404e4d5a89e09239b2accf43ff6d63
I want to return the signature to hello again. How I could do that, please?
I don't see any encrypt and decrypt function in elliptic, even in source code of library. In your demo code, it's a signature, not an encrypted message. You could use verify to validate the message whether is changed or not by some evil people..
console.log(myKey.verify(msg, derSign)); // true
console.log(myKey.verify(msg+"something_else", derSign)); // false
When the output is false, it's mean you message is changed, and true mean the message is not changed. That's how signature work, not encrypt or decrypt message.
So, if you want to encrypt and decrypt message with ecc, I guess you might use this library eccrypto.
I'm working on a project that uses an external API that is written in C#. In this API, I need to send some encrypted data while using their key that was provided when I started a session.
My project is built using NodeJS, so to do this encryption I am using the CryptoJS module. While talking with the API developer, he sent me a code showing how the encryption is made in C#. Here is the code with an example key and value to be encrypted.
TripleDESCryptoServiceProvider mDes = new TripleDESCryptoServiceProvider();
mDes.Key = Convert.FromBase64String("bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX");
mDes.Mode = CipherMode.ECB;
mDes.Padding = PaddingMode.Zeros;
ICryptoTransform mDesEnc = mDes.CreateEncryptor();
byte[] data = Encoding.UTF8.GetBytes("1"); //value to encrypt
var crypto = Convert.ToBase64String(mDesEnc.TransformFinalBlock(data, 0, data.Length));
Console.WriteLine(crypto);
This results in the following encryption: 3EAaQjY2dgA=
As you can see in the code or running it, the encryption uses 3DES, mode ECB, Zero Padding and the key while in a byte array format has 24 bytes.
So I started to recreate this code in JavaScript and ended up with this:
var CryptoJS = require("crypto-js");
var encryptStringWith3DES = function(toEncrypt, key){
toEncrypt = "1";
key = "bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX";
key = CryptoJS.enc.Utf8.parse(key);
console.log(toEncrypt + " " + key);
var encrypted = CryptoJS.TripleDES.encrypt(toEncrypt, key,{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
}).toString();
console.log(encrypted);
}
And it results in the following encryption: dj1byXBV6ug=
I have searched for many answers and none worked. My suspicion is with how CryptoJS receives the key as a parameter and how the key and data are parsed.
Does any of you know how to make my JS code result in the same encrypted data as the C# one?
I try to convert a string using AES method in JavaScript also I only need to use the CryptoJs library to achieve this.
When I try online from this website the result is coming as I expected which my Java program can decrypt it but when I try JavaScript I don't get the same result I get from the website.
This is what I need;
Data: {"test":1}
Secret: NdRgUkXp2s5v8y/A
The result should be: chib8X9Fnr7Vtn4VLRybKg==
The reason I'm referring the website, I don't know the mode and padding method of the above result but the below result is showing as expected from the server if you know the mode of the above result you can refer that also.
You can refer online encryption using https://www.devglan.com/online-tools/aes-encryption-decryption to validate.
This is what I get when I use JavaScript which is wrong;
var encrypted = CryptoJS.AES.encrypt('{"test",1}', "NdRgUkXp2s5v8y/A");
console.log(encrypted.toString())
Result: U2FsdGVkX1/GS5CecHJ10Z4qvSP8hY1NkDNtKGlg3OE=
Also it changes each time when generate.
I use this library https://cryptojs.gitbook.io/docs/
You pass the plain string value as a secret instead of UTF-8 encoded text and the value you get from the mentioned website is encrypted using PKCS7 padding method with ECB mode. Usually, this is the method most of the Android Java encryption methods support.
Encryption using CryptoJS.pad.Pkcs7 and make sure you provide the secret as UTF-8 as CryptoJS.enc.Utf8.parse(key) not in plain text.
let data = '{"test":1}'
let key = 'NdRgUkXp2s5v8y/A'
var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(encrypted.toString());
Decryption method
var decrypted = CryptoJS.AES.decrypt(encrypted.toString(), CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
console.log(decrypted.toString(CryptoJS.enc.Utf8))
The below example proves the encrypted value matches as expected.
let data = '{"test":1}'
let key = 'NdRgUkXp2s5v8y/A'
/*
* Encryption
*/
var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(encrypted.toString());
/*
* Decryption
*/
var decrypted = CryptoJS.AES.decrypt(encrypted.toString(), CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
console.log(decrypted.toString(CryptoJS.enc.Utf8) + "\n")
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
When you are printing out the decrypted string don't forget to add
.toString(CryptoJs.enc.utf8).
Check https://github.com/brix/crypto-js#plain-text-encryption
I am trying to replicate the Java code for AES Encryption and Decryption in Node JS.
Java Code
SecretKeySpec skeySpec;
String key = "a4e1112f45e84f785358bb86ba750f48";
public void encryptString(String key) throws Exception {
try {
skeySpec = new SecretKeySpec(key.getBytes(), "AES");
cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
byte encstr[] = cipher.doFinal(message.getBytes());
String encData = new String(encstr, "UTF-8");
System.out.println(encData);
} catch (NoSuchAlgorithmException nsae) {
throw new Exception("Invalid Java Version");
} catch (NoSuchPaddingException nse) {
throw new Exception("Invalid Key");
}
}
Node JS
var encryptKey = function (text) {
var cipher = crypto.createCipher('aes256', 'a4e1112f45e84f785358bb86ba750f48');
var crypted = cipher.update(text,'utf8', 'hex')
crypted += cipher.final('hex');
console.log(crypted);
return crypted;
}
I am unable to get the exact cipher-text in Node JS, which i am getting in Java.
Your code actually uses different encryption parameters in the 2 cases. AES, being a block cipher, takes: the plain text to encrypt, the initialization vector, also called IV (which is used in conjunction with the plaintext), and the encryption key.
In Java, the IV is, apparently, generated automatically on init() - from the Java SE platform docs for Cipher.init:
The generated parameters can be retrieved using getParameters or getIV
(if the parameter is an IV).
In Node.js, if using the deprecated createCipher function, the IV is generated automatically based on the provided key, probably in a different way than in Java, so you will get a different cipher text. However, you should be using the non-deprecated variant crypto.createCipheriv: https://nodejs.org/docs/latest-v12.x/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
In order to exactly reproduce the cipher text, you should:
Use the same encryption algorithm on both sides - it's best to specify this exactly, for example aes-256-cbc, or an authenticated encryption scheme such as aes-256-gcm, which is harder to use but provides message authentication.
Use the same IV on both sides, by providing it in the initialization params in Java, and by using createCipheriv in Node; though beware, you should always randomize it in production! See https://stackoverflow.com/a/20888967/6098312
As a closing remark, when using block encryption, you'll usually be generating securely-random IVs, which means the ciphertexts will always differ from one another, even for the same plaintext. This is a good thing! It protects your payload from an attacker who observes the encrypted data and makes conclusions based on message repetitions.
Finally after reviewing Java Docs and Node JS Crypto Docs managed to get the result.
We have to use crypto.createCipheriv() instead of crypto.createCipher with a iv.
Here iv will be null.
Code :
let crypto = require('crypto');
var iv = new Buffer.from(''); //(null) iv
var algorithm = 'aes-256-ecb';
var password = 'a4e1112f45e84f785358bb86ba750f48'; //key password for cryptography
function encrypt(buffer){
var cipher = crypto.createCipheriv(algorithm,new Buffer(password),iv)
var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
return crypted;
}
console.log(encrypt(new Buffer('TextToEncrypt')).toString())