Crypt in laravel Decrypt in react native Error - javascript

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().

Related

AES CTR 128 Decryption with key and iv values using CryptoJs Javascript

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.

TripleDES encryption has different results in C# and JavaScript (CryptoJS)

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?

AES Encryption/Decryption in Node JS similar to Java

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())

Decrypt AES on server side c# encrypted on client side javascript using sjcl

I am trying to decrypt some text encrypted client-side and having a difficult time making this happen.
I am using the Standford Javascript Crypto Library (sjcl) on client side which generates a json string that I can send to the server, something like this...
sjcl.encrypt("my_key", "something, something");
and produces this json string...
"{"iv":"tfyF7oMXjauOkRnwaffU3A==","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"bq5G63+hk0U=","ct":"KahF3hQ3FZZ2l7APxLB4nRvw03Xt/qD04AChoA=="}"
Now I receive this json string server-side, and tried to do this...
dynamic data = JObject.Parse(json);
var key = Encoding.ASCII.GetBytes("my_key");
var iv = Convert.FromBase64String(data.iv.Value);
byte[] cypher = Convert.FromBase64String(data.ct.Value);
string plainText = null;
using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
{
provider.Key = key;
provider.IV = iv;
ICryptoTransform decryptor = provider.CreateDecryptor(provider.Key, provider.IV);
using (MemoryStream ms = new MemoryStream(cypher))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
plainText = sr.ReadToEnd();
}
}
}
}
return plainText;
The server side code above crashes on plainText = sr.ReadToEnd; and throws a "The input data is not a complete block". I know that AES requires the cypherText to have a block size of 128 and since the text varies in size, how do I guarantee that it has a block size of 128 and not screw up the intended value? Does setting the padding necessary here?
Also, what's the corresponding mode for "ccm" in the AESCryptoServiceProvider? Do the "iter" & "salt" need to be in play in order to decrypt correctly?
Thanks in advance!
Jaime

Hashing a password using SHA256 and .NET/Node.js

Im Storing SHA256 hashes of user passwords in my database generated by .NET and I need to be able to check them with Node.js. The only problem is that .NET and Node.js create different hashes for the same password.
Password: ThisPassword
.NET:
var ue = new UnicodeEncoding();
var byteSourceText = ue.GetBytes("ThisPassword");
var byteHash = new System.Security.Cryptography.SHA256Managed().ComputeHash(byteSourceText);
return Convert.ToBase64String(byteHash);
//Tlwxyd7HIQhXkN6DrWJtmB9Ag2fz84P/QgMtbi9XS6Q=
Node.js (Using Crypto):
var crypto = require('crypto');
return crypto.createHash('sha256').update('ThisPassword').digest('base64')
//d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=
I found this, but was unable to figure out how to implement his solution.
Edit: You are using UTF-16 in C#, you must use same encoding in both languages:
Node.js:
var crypto = require("crypto");
var sha256 = crypto.createHash("sha256");
sha256.update("ThisPassword", "utf8");//utf8 here
var result = sha256.digest("base64");
console.log(result); //d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=
C#:
SHA256 sha256 = SHA256Managed.Create(); //utf8 here as well
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes("ThisPassword"));
string result = Convert.ToBase64String(bytes);
Console.WriteLine(result); //d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=
If you're using the .NET Framework's built-in SqlMembershipProvider Class from System.Web.Security, the hash incorporates a salt value as well as the password material when it is generated. Simply hashing the password alone in your node.js will never produce the same result as the hash in the database.
See Microsoft ASP.NET 2.0 Providers: Introduction for a link to .NET source code for the provider that will let you see how the salt value is applied.
You need to include your code if you need more help than this.
I created the node pbkdf2 module(source https://github.com/fundon/pbkdf2)
Required node >= 0.11.11
var pbkdf2 = require('pbkdf2');
var p = 'password';
var s = pbkdf2.generateSaltSync(32);
var pwd = pbkdf2.hashSync(p, s, 1, 20, 'sha256');
var bool = pbkdf2.compareSync(pwd, p, s, 1, 20, 'sha256');

Categories

Resources