I'm making an app that has to decrypt QRs and well... It doesn't, because i get the QR string but i cannot decrypt it.
I'm using this encryption method in VB.NET, and it works perfectly when i read an decrypt from VB.NET:
Private Function GetCodedQR(ByVal str As String) As String
Dim sToEncrypt As String = str
Dim encrypted() As Byte
' Create an Rijndael object
' with the specified key and IV.
Using rijAlg = Rijndael.Create()
rijAlg.Padding = PaddingMode.Zeros
rijAlg.Mode = CipherMode.CBC
rijAlg.KeySize = 256
rijAlg.BlockSize = 256
rijAlg.Key = System.Text.Encoding.ASCII.GetBytes("12345678912345678912345678912345")
rijAlg.IV = System.Text.Encoding.ASCII.GetBytes("123452hheeyy66#cs!9hjv887mxx7#8y")
' Create an encryptor to perform the stream transform.
Dim encryptor As ICryptoTransform = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(sToEncrypt)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
sToEncrypt = Convert.ToBase64String(encrypted)
Return sToEncrypt
End Function
But when im using JS (CryptoJS) to decrypt the message it just dont work!
var iv = CryptoJS.enc.Utf8.parse('123452hheeyy66#cs!9hjv887mxx7#8y');
var decrypted = CryptoJS.AES.decrypt(encrypted, '12345678912345678912345678912345', { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding });
Please help me I'm doing my best but JS is not my thing.
Related
I have been stuck in a long time. I am using Hybrid Crypto library in React Native to encrypt the message. Both public and private key are in PEM format.
let crypt = new Crypt({rsaStandard: 'RSA-OAEP'});
let encrypted = crypt.encrypt(publicKey, "This is a message");
return JSON.parse(encrypted).cipher;
This is the code I use to decrypt in Java. I followed this tutorial to read private key from pem file using bouncycastle library.
String str = "M2vFz/28sWhwAK4rGmnFAPRORRTlfa+XYpHFWQsi0bo=";
Security.addProvider(new BouncyCastleProvider());
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = generatePrivateKey(factory, RESOURCES_DIR + "private-key.pem");
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptOut = decryptCipher.doFinal(Base64.getDecoder().decode(str));
System.out.println(new String(decryptOut));
I've been trying many ways, the private key works fine when I decrypt in React but with Java I keep getting javax.crypto.BadPaddingException: Decryption error.
Updated Solution
Because I'm using hybrid crypto so it will include RSA + AES
Flow in frondend: Using AES key to encrypt text => Using public RSA key to encrypt AES key. Then you send everything you need to decrypt (encrypted AES key, Iv, and cipher text)
let crypt = new Crypt({rsaStandard: 'RSAES-PKCS1-V1_5',aesIvSize: 16});
let encrypted = crypt.encrypt(publicKey, str);
const encryptedObj = JSON.parse(encrypted);
return Object.values(encryptedObj.keys)[0] + ',' + encryptedObj.iv + ',' + encryptedObj.cipher;
Flow in java: Using RSA private key to decrypt AES key => Using AES key + Iv to decrypt cipher text
PrivateKey privateKey = generatePrivateKey();
Cipher decryptCipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] keyb = decryptCipher.doFinal(Base64.getDecoder().decode(AESkey));
SecretKeySpec skey = new SecretKeySpec(keyb, "AES");
IvParameterSpecivspec = new IvParameterSpec(Base64.getDecoder().decode(iv));
decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, skey, ivspec);
byte[] decryptOut = decryptCipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decryptOut);
I am trying to decrypt a value (encrypted in des) coming from VB.
When I try to decrypt the encryptedValue using crypto in Javascript the output gives me an empty value.
I have attached how the encryption was done in VB.
HOW I AM TRYING TO DECRYPT IN JAVASCRIPT
var CryptoJS = require("crypto-js");
var key = "peekaboo";
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";
encryptedValue = CryptoJS.enc.Base64.parse(encryptedValue);
var data = CryptoJS.DES.decrypt(encryptedValue, key, { iv: "cbauthiv" });
const email = data.toString(CryptoJS.enc.Utf8);
console.log(email, "ORIGINAL TEXT");
THE WAY IT IS ENCRYPTED IN VB
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module Module1
Private Const ENCRYPTIONKEY As String = "peekaboo"
Sub Main()
Dim s As String = Encrypt("ditzymoose#outlook.com")
Dim r As String = Decrypt(s)
Console.ReadLine()
End Sub
Private Function Encrypt(stringToEncrypt As String) As String
Dim rng As New RNGCryptoServiceProvider
Dim byteArray() As Byte = New Byte(8) {}
Dim iv_value As String = "cbauthiv"
Dim key() As Byte = {}
Dim IV() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(iv_value, 8))
key = System.Text.Encoding.UTF8.GetBytes(Left(ENCRYPTIONKEY, 8))
Dim des As New DESCryptoServiceProvider
rng.GetBytes(byteArray)
Dim Salt As String = BitConverter.ToString(byteArray)
Dim SaltedInput As String = Salt & "~" & stringToEncrypt
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function
End Module
The key and IV must be passed as WordArray. For the conversion the Utf8-Encoder has to be used, here.
Also, the ciphertext must be passed as a CipherParams object or alternatively Base64 encoded (which is then implicitly converted to a CipherParams object), here.
With these changes the ciphertext of the VB code can be successfully decrypted using the CryptoJS code:
var key = CryptoJS.enc.Utf8.parse("peekaboo");
var iv = CryptoJS.enc.Utf8.parse("cbauthiv");
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";
var data = CryptoJS.DES.decrypt(encryptedValue, key, {iv: iv});
var email = data.toString(CryptoJS.enc.Utf8);
console.log(email, "ORIGINAL TEXT");
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
Please note that DES is insecure (here) and was replaced by AES almost 20 years ago. Also insecure is a static IV. Instead, a random IV should be generated for each encryption.
Furthermore a password should not be used as key. If a password is to be used, the key should be derived from the password using a reliable key derivation function such as PBKDF2.
I am using Java to encrypt a text payload with Triple DES. First I create an ephemeral key that I will use for encrypting the payload:
private byte[] createEphemeralKey() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(168);
return keygen.generateKey().getEncoded();
}
Then I encrypt my payload with said key:
private String encryptTripleDES(byte[] ephemeralKey, String payload) throws Exception {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = payload.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.getEncoder().encodeToString(cipherText);
}
Also need a padding function to ensure the data length is divisable by 8:
private String adjustPadding(String input, int blockSize) {
int len = input.length() % blockSize;
int paddingLength = (len == 0) ? 0 : (blockSize - len);
while (paddingLength > 0) {
input += "F";
paddingLength--;
}
return input;
}
And here is my process end to end:
String data = "Marnus"
byte[] = ephemeralKey = createEphemeralKey();
String adjustedData = adjustPadding (data,8);
String encryptedPayload = encryptTripleDES(ephemeralKey, adjustedData);
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
So I take the 2 variables encryptedPayload and encodedKey, that are both Base64 encoded string, and send it off via HTTP to node express app.
In the Javascript side of things, I use node-forge - Here is the part of my express app that does the decryption:
let nodeBuffer = Buffer.from(data, 'base64')
let input = forge.util.createBuffer(nodeBuffer.toString('binary'))
// 3DES key and IV sizes
let keySize = 24;
let ivSize = 8;
let derivedBytes = forge.pbe.opensslDeriveBytes(ephemeralKey, null, keySize + ivSize);
let buffer = forge.util.createBuffer(derivedBytes);
let key = buffer.getBytes(keySize)
let iv = buffer.getBytes(ivSize)
let decipher = forge.cipher.createDecipher('3DES-ECB', key)
decipher.start({iv: iv})
decipher.update(input)
console.log('decipher result', decipher.finish())
let decryptedResult = decipher.output.data;
Here is an Triples DES example in the node-forge docs:
A few notes:
I create a node-forge buffer from a regular buffer since I don't have a input file like the examples gives. Here is how the docs states one should create one buffer from the other:
*I use base64 as that is what I used in the java side to encode the data that was sent.
Then, I dont have a salt so I left the 2'nd param null in opensslDeriveBytes as specified in the docs I should do.
Thirdly, I am also not sure if my keysize of 24 is correct?
My results
So doing an end to end test yields the following:
In my Java app, the test data was "Marnus", the encryptedPayload was ez+RweSAd+4= and the encodedKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu.
Then in my javascript code data was obviously ez+RweSAd+4=(encryptedPayload) and the ephemeralKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu(encodedKey).
After the decryption ran, the value of decryptedResult was ©ýÕ?µ{', which is obviously just garbage since it was not encoded yet, but I cant figure out which encoding to use?
I tried using forge.util.encode64(decipher.output.data), but that just gave me qf3VP7UYeyc=, which is not right.
For what it's worth, here is the type that decipher.output
With a lot more tweaking and testing different options, I got it working - and the good news is I managed to get it all working with the built in crypto library in nodejs (v12.18.4).
First things first, the JAVA side just needs a change to the key size (from 168 to 112), the rest remains the same - see below example as one single method (should be split up in final implementation of course for testability and usability):
//Some data:
String payload = "{\"data\":\"somedata\"}";
// Create Key
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(112);
byte[] ephemeralKey = keygen.generateKey().getEncoded();
// Adjust the data, see adjustPadding method in the question for details.
String data = adjustPadding (payload,8);
// Wil now be "{"data":"somedata"}FFFFF", can just chop off extra in JS if need be. When sending JSON one knows the end of the object will always be "}"
// Do Encrypt
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = data.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
String encryptedPayload = Base64.getEncoder().encodeToString(cipherText);
//Lastly, Base64 the key so you can transport it too
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
on the Javascript side of things we keep it simple:
// I'm using TS, so change the import if you do plain JS
import crypto = require('crypto')
//need bytes from the base64 payload
let buff = Buffer.from(ephemeralKey, 'base64')
const decipher = crypto.createDecipheriv('des-ede3', buff, null)
decipher.setAutoPadding(false)
let decrypted = decipher.update(data, 'base64', 'utf8')
decrypted += decipher.final('utf8')
console.log(decrypted)
//{"data":"somedata"}FFFFF"
I am using CryptoJS in my angular app to implement AES encryption but I am keep getting TypeError: Cannot read property '0' of undefined error when I try to send empty 16 byte array in IV
Here's my typescript code:
aesEncrypt(keys: string, value: string) { // encrypt api request parameter with aes secretkey
var key = CryptoJS.enc.Utf8.parse(keys);
//var iv = CryptoJS.enc.Utf8.parse(keys);
var iv = new Uint16Array(16);
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(value), key,
{
//keySize: 256,
keySize: 128,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
But same thing works fine in .NET, android, ios when I send empty 16 byte array in IV
.NET code:
private static AesCryptoServiceProvider AesCryptoServiceProvider(string key)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Encoding.UTF8.GetBytes(key);
//aes.IV = Encoding.UTF8.GetBytes(key);
aes.IV = new byte[16];
return aes;
}
android code:
public static String encryptURLEncoding(byte[] key, String encryption) throws GeneralSecurityException
{
if (key.length != 16)
{
throw new IllegalArgumentException("Invalid key size.");
}
// Setup AES tool.
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] dstBuff = cipher.doFinal(encryption.getBytes());
String encryptedStringData = android.util.Base64.encodeToString(dstBuff, android.util.Base64.DEFAULT);
return encryptedStringData;
}
I want to implement AES encrypt decrypt by providing empty 16 byte array because this app is interconnected with my other apps which are on android, ios platform with same encryption setup but I am getting error in my angular app, How can I resolve this issue?
In the JavaScript code the IV must be passed as WordArray. Since a 0-IV was used in the C# code, this must also be done in the JavaScript code. The corresponding WordArray could be e.g.
var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
Note that the Hex encoder is used so that the 16 bytes 0-IV correspond to 32 0-values.
Also be aware that generally a 0-IV should only be used for testing purposes. In practice, for security reasons, a random IV has to be generated for each encryption. Additionally, a key / IV pair may only be used once.
Furthermore CryptoJS does not know the parameter keySize and ignores it. The used AES variant is determined by the key size, e.g. for a 32 bytes key AES-256 is applied, here.
For those who faced a similar error in typescript for encrypting a string, you just need to import the package this way
import * as Crypto from 'crypto-js';
I faced the same problem.
Including the iv option solved it.
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f"); var ciphertext = CryptoJS.AES.encrypt("msg", CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f"),{ iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.AnsiX923 });
I am using CryptoJS to encrypt a message and send it to the server, and decrypting it on the other end in C# using Aes Manager. I get a response back when I send it to the server, but it isn't correct.
Javascript:
this.CryptoJS=require("crypto-js");
var temp=this.CryptoJS.AES.encrypt("hello","yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey",{
keySize:128/8,
iv:this.CryptoJS.enc.Utf8.parse("helllooohelllooo"),
mode:this.CryptoJS.mode.CBC,
padding:this.CryptoJS.pad.ZeroPadding
});
data.text=temp.toString(); // This is how I send it to the server
C#:
byte[] Key = UTF8Encoding.UTF8.GetBytes("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");
byte[] toBytes = UTF8Encoding.UTF8.GetBytes("helllooohelllooo");
AesManaged aes = new AesManaged();
aes.Key = Key;
aes.IV = toBytes;
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.KeySize = 128;
aes.BlockSize = 128;
byte[] bytes = Convert.FromBase64String(data.text);
UTF8Encoding utf8 = new UTF8Encoding();
using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
MemoryStream MS = new MemoryStream(bytes);
CryptoStream CS = new CryptoStream(MS, decryptor, CryptoStreamMode.Write);
CS.Write(bytes, 0, bytes.Length);
CS.FlushFinalBlock();
MS.Position = 0;
bytes = new byte[MS.Length];
MS.Read(bytes, 0, bytes.Length);
Plaintext = utf8.GetString(bytes);
var temp = 5;
}
This is what I get as a result from the Plaintext variable: t�k�\a``\u007f������\f^,F~\u0017�\u001fp��#5�\u007f\\
You should explicitly pass the key, plaintext and IV as binary data rather than strings:
let iv = CryptoJS.enc.Utf8.parse("helllooohelllooo");
let pt = CryptoJS.enc.Utf8.parse("hello");
let key = CryptoJS.enc.Utf8.parse("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");
Then use in the code like so:
CryptoJS.AES.encrypt(pt, key, ...);
Note that your use of zero padding, fixed IV, and no HMAC or AEAD mode makes the code you have completely insecure. You definitely should not use it. Consult this GitHub repository for examples of secure encryption between JavaScript and C#.
I was able to fix my problem i was not converting the original key to utf8 and once i did that it fixed itself
Resource