I am trying to encrypt a piece of string in nodejs and need to decrypt that in front end javascript. In nodejs I was using the crypto library and in front end using web crypto.
Facing some error while decrypting in the front end.
NodeJS
const crypto = require('crypto');
const iv = crypto.randomBytes(12);
const algorithm = 'aes-256-gcm';
let password = 'passwordpasswordpasswordpassword';
let text = 'Hello World!';
let cipher = crypto.createCipheriv(algorithm, password, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
let cipherObj = {
content: encrypted,
tag: tag,
iv: iv
}
Front End
let cipherObj; //GET FROM BE
let aesKey = await crypto.subtle.importKey(
"raw",
Buffer.from('passwordpasswordpasswordpassword'), //password
"AES-GCM",
true,
["decrypt"]
);
let decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: Buffer.from(cipherObj.iv),
tagLength: 128
},
aesKey,
Buffer.concat([Buffer.from(cipherObj.content), Buffer.from(cipherObj.tag)])
);
Decrypt function in the front-end is throwing an error.
ERROR Error: Uncaught (in promise): OperationError
at resolvePromise (zone.js:814)
at zone.js:724
at rejected (main.js:231)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3820)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3811)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
PS: I am using Angular 7 in front end
I was able to get this working with some changes:
I use SHA-256 to hash the password, so it can be any length. (The OP requires a 32-byte string.)
I added additional helper functions from another answer for converting buffers to/from hex.
I print the output cipherObj in JSON. This is your encrypted message payload.
Helpers - NodeJS and Browser
// look up tables
var to_hex_array = [];
var to_byte_map = {};
for (var ord=0; ord<=0xff; ord++) {
var s = ord.toString(16);
if (s.length < 2) {
s = "0" + s;
}
to_hex_array.push(s);
to_byte_map[s] = ord;
}
// converter using lookups
function bufferToHex2(buffer) {
var hex_array = [];
//(new Uint8Array(buffer)).forEach((v) => { hex_array.push(to_hex_array[v]) });
for (var i=0; i<buffer.length; i++) {
hex_array.push(to_hex_array[buffer[i]]);
}
return hex_array.join('')
}
// reverse conversion using lookups
function hexToBuffer(s) {
var length2 = s.length;
if ((length2 % 2) != 0) {
throw "hex string must have length a multiple of 2";
}
var length = length2 / 2;
var result = new Uint8Array(length);
for (var i=0; i<length; i++) {
var i2 = i * 2;
var b = s.substring(i2, i2 + 2);
result[i] = to_byte_map[b];
}
return result;
}
The backend uses hex2buffer and the frontend uses buffer2hex, but you can just include that code in both.
So the backend code is the above helpers plus:
NodeJS
const crypto = require('crypto');
const iv = crypto.randomBytes(12);
const algorithm = 'aes-256-gcm';
let password = 'This is my password';
let key = crypto.createHash("sha256").update(password).digest();
let text = 'This is my test string, with 🎉 emoji in it!';
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
let cipherObj = {
content: encrypted,
tag: bufferToHex2(tag),
iv: bufferToHex2(iv)
}
console.log(JSON.stringify(cipherObj));
The output changes every run due to random IV, but for example:
{"content":"22da4796365ac1466f40022dd4510266fa3e24900b816f365e308cf06c95237783d1043c7deeb45d00381f8ff9ed","tag":"b7007905163b2d4890c9452c8edc1821","iv":"eb4758787164f95ac22ee50d"}
So then the example frontend code is the above helper functions, plus:
Browser
let cipherObj; //GET FROM BACKEND
// For example:
cipherObj = {"content":"22da4796365ac1466f40022dd4510266fa3e24900b816f365e308cf06c95237783d1043c7deeb45d00381f8ff9ed","tag":"b7007905163b2d4890c9452c8edc1821","iv":"eb4758787164f95ac22ee50d"}
let password = 'This is my password';
let enc = new TextEncoder();
let key = await window.crypto.subtle.digest({ name:"SHA-256" }, enc.encode(password));
let aesKey = await crypto.subtle.importKey(
"raw",
key,
"AES-GCM",
true,
["decrypt"]
);
let decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: hexToBuffer(cipherObj.iv),
tagLength: 128
},
aesKey,
hexToBuffer(cipherObj.content + cipherObj.tag)
);
let dec = new TextDecoder();
console.log(dec.decode(decrypted));
// This is my test string, with 🎉 emoji in it!
Some crypto reference examples.
Related
I have the following code for decryption in java, I want that to be implemented in nodejs but the i found many tuto for my problem but they use a salt and that don't work when i try to remove the salt system.
My olds functions from java
public void readLastLogin(File lastLogin) {
try {
final Cipher ciph = this.openCipher(Cipher.DECRYPT_MODE);
final DataInputStream dis = new DataInputStream(new CipherInputStream(new FileInputStream(lastLogin), ciph));
String user = dis.readUTF();
String token = dis.readUTF();
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveLastLogin(File lastLogin, String user, String token) {
try {
final Cipher ciph = this.openCipher(Cipher.ENCRYPT_MODE);
final DataOutputStream dos = new DataOutputStream(new CipherOutputStream(new FileOutputStream(lastLogin), ciph));
dos.writeUTF(user);
dos.writeUTF(token);
dos.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
private Cipher openCipher(final int mode) throws Exception {
final Random rnd = new Random(43287234L);
final byte[] data = new byte[8];
rnd.nextBytes(data);
final PBEParameterSpec spec = new PBEParameterSpec(data, 5);
final SecretKey key = SecretKeyFactory
.getInstance("PBEWithMD5AndDES")
.generateSecret(new PBEKeySpec("mysecretpassword".toCharArray()));
final Cipher ret = Cipher.getInstance("PBEWithMD5AndDES");
ret.init(mode, key, spec);
return ret;
}
I try this but not working
KDF(password, iterations) {
var key = new Buffer(password,'utf-8');
var i;
for (i = 0; i < iterations; i+=1) {
key = crypto.createHash("md5").update(key).digest();
}
return key;
}
getKeyIV(password, iterations) {
var key = this.KDF(password, iterations);
var keybuf = new Buffer(key,'binary').slice(0,8);
var ivbuf = new Buffer(key,'binary').slice(8,16);
return [ keybuf, ivbuf ];
}
decrypt(message) {
var kiv = this.getKeyIV('password' ,5);
var decipher = crypto.createDecipheriv('des-ede', kiv[0], kiv[1]);
var result = decipher.update(message, 'hex', 'utf-8');
return result + decipher.final('utf-8');
}
Edit: The salt generated at runtime of the Java code is hex encoded: 0x0C9D4AE41E8315FC
final byte[] data = new byte[8];
data[0] = 12;
data[1] = -99;
data[2] = 74;
data[3] = -28;
data[4] = 30;
data[5] = -125;
data[6] = 21;
data[7] = -4;
There are three issues in the code:
The Java code uses writeUTF(). This is based on modified UTF-8, with two additional bytes prepended to contain the data size. A NodeJS library for modified UTF-8 is mutf-8.
Instead of des-ede (3DES/2TDEA in ECB mode), des-cbc (DES in CBC mode) must be applied. If DES is not available in the used NodeJS version, it can be mimicked with 3DES/2TDEA in CBC mode, des-ede-cbc, where the 8 bytes key has to be concatenated with itself to a 16 bytes key, reducing 3DES to DES. This workaround has the disadvantage of a performance loss.
The Java code applies a static 8 byte salt because Random() is instantiated with a static seed. This salt can be determined at runtime to (hex encoded): 0x0C9D4AE41E8315FC.
pbewithmd5anddes-js is a port of PBEWithMD5AndDES to NodeJS, from which the KDF(), getKeyIV() and decrypt() methods can be used, but must be adapted taking into account the above points. In addition, the functionality of readUTF() (the counterpart of writeUTF()) must be implemented. One possible solution is:
var crypto = require('crypto');
const { MUtf8Decoder } = require("mutf-8");
var pbewithmd5anddes = {
KDF: function(password,salt,iterations) {
var pwd = Buffer.from(password,'utf-8');
var key = Buffer.concat([pwd, salt]);
var i;
for (i = 0; i < iterations; i+=1) {
key = crypto.createHash('md5').update(key).digest();
}
return key;
},
getKeyIV: function(password,salt,iterations) {
var key = this.KDF(password,salt,iterations);
var keybuf = Buffer.from(key,'binary').subarray(0,8);
var ivbuf = Buffer.from(key,'binary').subarray(8,16);
return [ keybuf, ivbuf ];
},
decrypt: function(payload,password,salt,iterations) {
var encryptedBuffer = Buffer.from(payload,'base64');
var kiv = this.getKeyIV(password,salt,iterations);
//var decipher = crypto.createDecipheriv('des-cbc', kiv[0], kiv[1]); // Fix 1: If supported, apply DES-CBC with key K
var decipher = crypto.createDecipheriv('des-ede-cbc', Buffer.concat([kiv[0], kiv[0]]), kiv[1]); // otherwise DES-EDE-CBC with key K|K
var decryptedBuf = Buffer.concat([decipher.update(encryptedBuffer), decipher.final()])
var decrypted = this.readUTF(decryptedBuf) // Fix 2: apply writeUTF counterpart
return decrypted;
},
readUTF: function(decryptedBuf) {
var decoder = new MUtf8Decoder()
var decryptedData = []
var i = 0;
while (i < decryptedBuf.length){
var lengthObj = decryptedBuf.readInt16BE(i);
var bytesObj = decryptedBuf.subarray(i+2, i+2+lengthObj);
var strObj = decoder.decode(bytesObj)
decryptedData.push(strObj)
i += 2 + lengthObj;
}
return decryptedData;
}
};
Test:
On the Java side, the following is executed:
saveLastLogin(file, "This is the first plaintext with special characters like §, $ and €.", "This is the second plaintext with special characters like §, $ and €.");
The raw ciphertext written to file is Base64 encoded:
Ow8bdeNM0QpNFQaoDe7dhG3k9nWz/UZ6v3+wQVgrD5QvWR/4+sA+YvqtnQBsy35nQkwhwGRBv1h1eOa587NaFtnJUWVHsRsncLWZ05+dD2rYVpcZRA8s6P2iANK6yLr+GO/+UpZpSe0fA4fFqEK1nm3U7NXdyddfuOlZ3h/RiyxK5819LieUne4F8/TpMzT0RIWkxqagbVw=
This can be decrypted on the NodeJS side with:
var payload = 'Ow8bdeNM0QpNFQaoDe7dhG3k9nWz/UZ6v3+wQVgrD5QvWR/4+sA+YvqtnQBsy35nQkwhwGRBv1h1eOa587NaFtnJUWVHsRsncLWZ05+dD2rYVpcZRA8s6P2iANK6yLr+GO/+UpZpSe0fA4fFqEK1nm3U7NXdyddfuOlZ3h/RiyxK5819LieUne4F8/TpMzT0RIWkxqagbVw=';
var password = 'mysecretpassword';
var salt = Buffer.from('0C9D4AE41E8315FC', 'hex');
var iterations = 5;
var decrypted = pbewithmd5anddes.decrypt(payload,password,salt,iterations);
console.log(decrypted);
with the output:
[
'This is the first plaintext with special characters like §, $ and €.',
'This is the second plaintext with special characters like §, $ and €.'
]
Note that the code contains serious vulnerabilities:
PBEWithMD5AndDES uses a key derivation based on the broken MD5 digest (PBKDF1), and as encryption algorithm the deprecated DES (officially withdrawn almost 20 years ago).
Use of a static salt.
An iteration count of 5 is generally much too small.
Random() (unlike SecureRandom()) is not cryptographically strong. Also note that it is not a good idea to use a PRNG like Random() for deterministic key derivation, as the implementation may change, leading to different results even with the same seed.
Our application has a group chat feature which involves end-to-end encryption of group chat messages.
The group is hosted at server.
All the encryption and decryption is handled on the clientside.
It also utilizes the same mechanism of encryption for the real-time messages.
The group chat works by foremost someone creating this group at serverside, when a client is instating its creation they generate a new key [clientside], and validate it on their end [successful encryption and decryption of a same static text from SubtleCrypto], and then successfully hosts it by sending the encrypted buffer to server where groups are managed, storing it, and then others can join if they know the secret key. We use the same AES-GCM Symmetric Key / Secret Key that is generated for this purpose. The server-side doesn't have the key stored anywhere.
Now, to validate whether the key a client trying to join this group is valid or not before joining is, with the key that was shared to them [by other means, such as email etc], at client-side, encrypt the SAME static text, and send its buffer. Then the buffer value stored at the server-side on creation time is compared to this new client joining with the buffer of the newly encrypted static text they performed on client-side, and if the buffer is equal on server-side, they are authorized into this group.
Now with reference to my previous question(s), I'm attempting to replace Web API SubtleCrypto to SJCL, and the newly generated SJCL encrypted buffer is never the same compared to the SubtleCrypto. While encrypting and decrypting between each other is already established, the problem at hand is that their buffers don't match, even though they're both using the same key, IV, and AES-GCM mode. And they both have to simultaneously work for backwards compatibility of different client versions.
Here is an example:
const buf2hex = (buffer) =>
{
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
const string2hex = (input) =>
{
let hex;
let result = "";
let i = 0;
for (i = 0; i < input.length; i++)
{
hex = input.charCodeAt(i).toString(16);
result += ("000" + hex).slice(-4);
}
return result
}
const hex2bytes = (string) =>
{
const normal = string.length % 2 ? "0" + string : string; // Make even length
const bytes = new Uint8Array(normal.length / 2);
for (let index = 0; index < bytes.length; ++index)
{
const c1 = normal.charCodeAt(index * 2);
const c2 = normal.charCodeAt(index * 2 + 1);
const n1 = c1 - (c1 < 58 ? 48 : 87);
const n2 = c2 - (c2 < 58 ? 48 : 87);
bytes[index] = n1 * 16 + n2;
}
return bytes;
}
//JWK K Value
const generateKey = async () =>
{
const key = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 128
}, true, ["encrypt", "decrypt"]);
const key_exported = await window.crypto.subtle.exportKey("jwk", key);
return key_exported.k;
}
//CryptoKey generated from SubtleCrypto:
const generateSubtleCryptoKey = async (kvalue) =>
{
return window.crypto.subtle.importKey(
"jwk",
{
k: kvalue,
alg: "A128GCM",
ext: true,
key_ops: ["encrypt", "decrypt"],
kty: "oct",
},
{
name: "AES-GCM",
length: 128
},
false,
["encrypt", "decrypt"]
);
}
//Cipher generated from SJCL:
const generateCipherSJCL = (kkey) =>
{
const ekkeyB64 = kkey.replace(/-/g, '+').replace(/_/g, '/'); // Base64url -> Base64 (ignore optional padding)
const ebkey = sjcl.codec.base64.toBits(ekkeyB64); // conert to bitArray
const ecipher = new sjcl.cipher.aes(ebkey);
return ecipher;
}
const encryptText = "STATIC TEXT";
const compareBuffers = async () =>
{
const kkey = await generateKey();
const cryptokey = await generateSubtleCryptoKey(kkey)
const ecipher = generateCipherSJCL(kkey);
const subtleCrypto = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: new Uint8Array(12)
}, cryptokey, new TextEncoder().encode(JSON.stringify(encryptText)));
const encryptionIv = sjcl.codec.hex.toBits(buf2hex(new Uint8Array(12).buffer));
const encryptedMessageFormat = sjcl.codec.hex.toBits(string2hex(JSON.stringify(encryptText)));
const sjclEncrypted = sjcl.mode.gcm.encrypt(ecipher, encryptedMessageFormat, encryptionIv);
const originalEncryptedSJCL = Buffer.from(sjclEncrypted);
console.log({subtleCrypto});
console.log({originalEncryptedSJCL});
const e1 = Buffer.from(new Uint8Array(sjclEncrypted));
const e2 = Buffer.from(new Uint8Array(subtleCrypto));
console.log({e1, e2}); //{e1: Uint8Array(11), e2: Uint8Array(29)}
console.log(Buffer.compare(e1, e2)); //should be 0, equal buffer.
}
compareBuffers();
I suppose I should preface this by stating that I have very limited cryptography knowledge, but why would the buffers differ when they're both encrypted and decrypted across both libraries when the mechanism is same?
I want the below java code to be converted into nodejs
JAVA
SecretKeySpec skeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] buf = data.getBytes("UTF-8");
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
baos.write(buf);
int len = 16 - (baos.size() % 16);
baos.write(new byte[len]);
buf = baos.toByteArray();
}
buf = cipher.doFinal(buf);
final String data2 = Base64.encodeBase64String(buf);
I have done it using crypto but due to the padding issue i am not able to execute cipher.final. Any ideas to resolve this issue?
NodeJS
const crypto = require('crypto');
var keybase64 = Buffer.from(app_secret, 'utf8');
var data1 = Buffer.from(data, 'utf8');
let cipher = crypto.createCipheriv('aes-256-ecb', app_secret, '');
cipher.setAutoPadding(false);
let result = cipher.update(data1,'utf8','base64');
result += cipher.final('base64')
console.log('result', result)
Implemented in javascript using cryptojs but unable to do the same in swift using cryptoswift. I am unable to understand how key, iv & ciphertext are generated in javascript looking at the below code. Out of ideas to do the same in Swift using cryptoswift.
decryptPayloadQR(ciphertextStr, SecretKey) {
try {
let key = CryptoJS.enc.Utf8.parse(SecretKey);
var ciphertext = CryptoJS.enc.Base64.parse(ciphertextStr);
var iv = ciphertext.clone();
iv.sigBytes = 16;
iv.clamp();
ciphertext.words.splice(0, 4);
ciphertext.sigBytes -= 16;
var decrypted = CryptoJS.AES.decrypt({ ciphertext: ciphertext }, key, {
iv: iv
});
console.log("===decrypted.toString(CryptoJS.enc.Utf8)=",decrypted.toString(CryptoJS.enc.Utf8));
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (error) {
console.log("===error in decrpt fun === : ",error);
return false
}
}
Result is string which can be converted to json.
Swift code below.
let encryptedString = "OdqBIN4twOxKwe1aIZhTatkzVdfvN/mfB2Arra38tF25+3efc+Kl+HABZtqiGrTIihSpfW/XHW8+31Rl+uHZB2immfB6/w8E2j5ylCV8RKrqHVMMB7BPBLyr8oTuxmYEla1J1NxywLFPyNZCI4zmkYczwVSyssd5VKWH8WaBHR5Yai6MaxugdohW40byPx6xqbhwjHN5w+dh3dJBSFbM5EhQTqPwfBA1v1UBrCXooay47keSFor/7ywjV3e2bU5JrL0o+S26UF6zoVkRP1tdGAY3TqYyrPLUHVq0nIzkmnZdQk5gFGjN0sF58WdhuqjgRAtSrbmL5biuOtmQHFmNx4sUjkF4pYvfYxrj3ze2H/6G03cxCzW/DUytV678IBrd"
//======== iv & cipher text should be same as generated in above javascript code ==========//
//======== Should these keys be in hex =======//
let iv = "" /* No idea how to get iv from encrypted string */
let cipherText = "" /* No idea how to get cipherText from encrypted string */
let key = "abababababababab"
do {
let decryptor = try AES(key: key, iv: iv)
let decryptedBytes = try decryptor.decrypt(cipherText.bytes)
print(String(bytes: decryptedBytes, encoding: .utf8)!)
} catch {
print(error)
}
How do I get iv, key & cipher text for swift similar to that in javascript?
Thanks in advance.
I was able to do the same in Swift with cryptoswift using below code.
let encryptedString = "OdqBIN4twOxKwe1aIZhTatkzVdfvN/mfB2Arra38tF25+3efc+Kl+HABZtqiGrTIihSpfW/XHW8+31Rl+uHZB2immfB6/w8E2j5ylCV8RKrqHVMMB7BPBLyr8oTuxmYEla1J1NxywLFPyNZCI4zmkYczwVSyssd5VKWH8WaBHR5Yai6MaxugdohW40byPx6xqbhwjHN5w+dh3dJBSFbM5EhQTqPwfBA1v1UBrCXooay47keSFor/7ywjV3e2bU5JrL0o+S26UF6zoVkRP1tdGAY3TqYyrPLUHVq0nIzkmnZdQk5gFGjN0sF58WdhuqjgRAtSrbmL5biuOtmQHFmNx4sUjkF4pYvfYxrj3ze2H/6G03cxCzW/DUytV678IBrd"
let aesIVBlockSize = 16
let cipherData = Data(base64Encoded: encryptedString, options: .ignoreUnknownCharacters)
let ivBytes = Array(Array(cipherData!).dropLast(cipherData!.count - aesIVBlockSize))
let actualCipherBytes = Array(Array(cipherData!).dropFirst(aesIVBlockSize))
do {
let aes = try AES(key: Array("abababababababab".data(using: .utf8)!), blockMode: CBC(iv: ivBytes))
let decrypted = try aes.decrypt(actualCipherBytes)
let outData = Data(bytes: decrypted)
print(outData)
print(String(bytes: outData, encoding: .utf8) as Any)
} catch {
print("Decryption error: \(error)")
}
I am trying to write two classes in C# and Javascript which I can use throughout my project to encrypt or decrypt data using AES when data is exchanged.
Using AES I am embedding the Salt (32 bytes) and IV (16 bytes) in the encrypted result, this works fine for both classes individually when testing. Adding the Salt and IV to the mix doesn't bring up a lot of references to get this working between the two platforms.
For C# I am using the standard System.Security.Crypthography.AES
private static readonly int iterations = 1000;
public static string Encrypt(string input, string password)
{
byte[] encrypted;
byte[] IV;
byte[] Salt = GetSalt();
byte[] Key = CreateKey(password, Salt);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.CBC;
aesAlg.GenerateIV();
IV = aesAlg.IV;
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
encrypted = msEncrypt.ToArray();
}
}
}
byte[] combinedIvSaltCt = new byte[Salt.Length + IV.Length + encrypted.Length];
Array.Copy(Salt, 0, combinedIvSaltCt, 0, Salt.Length);
Array.Copy(IV, 0, combinedIvSaltCt, Salt.Length, IV.Length);
Array.Copy(encrypted, 0, combinedIvSaltCt, Salt.Length + IV.Length, encrypted.Length);
return Convert.ToBase64String(combinedIvSaltCt.ToArray());
}
public static string Decrypt(string input, string password)
{
byte[] inputAsByteArray;
string plaintext = null;
try
{
inputAsByteArray = Convert.FromBase64String(input);
byte[] Salt = new byte[32];
byte[] IV = new byte[16];
byte[] Encoded = new byte[inputAsByteArray.Length - Salt.Length - IV.Length];
Array.Copy(inputAsByteArray, 0, Salt, 0, Salt.Length);
Array.Copy(inputAsByteArray, Salt.Length, IV, 0, IV.Length);
Array.Copy(inputAsByteArray, Salt.Length + IV.Length, Encoded, 0, Encoded.Length);
byte[] Key = CreateKey(password, Salt);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new MemoryStream(Encoded))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
catch (Exception e)
{
return null;
}
}
public static byte[] CreateKey(string password, byte[] salt)
{
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterations))
return rfc2898DeriveBytes.GetBytes(32);
}
private static byte[] GetSalt()
{
var salt = new byte[32];
using (var random = new RNGCryptoServiceProvider())
{
random.GetNonZeroBytes(salt);
}
return salt;
}
For the Javascript solution I am using CryptoJS, based upon this reference http://www.adonespitogo.com/articles/encrypting-data-with-cryptojs-aes/
var keySize = 256;
var ivSize = 128;
var saltSize = 256;
var iterations = 1000;
var message = "Hello World";
var password = "Secret Password";
function encrypt (msg, pass) {
var salt = CryptoJS.lib.WordArray.random(saltSize/8);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var iv = CryptoJS.lib.WordArray.random(ivSize/8);
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
// salt, iv will be hex 32 in length
// append them to the ciphertext for use in decryption
var transitmessage = salt + iv + encrypted;
return transitmessage.toString();
}
function decrypt (transitmessage, pass) {
var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 64));
var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(64, 32));
var encrypted = transitmessage.substring(96);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
})
return decrypted.toString(CryptoJS.enc.Utf8);
}
Used password: Secret Password
C# outcome:
r7Oi1vMXZ5mYJay8i+slbJZEiT3CxV/1zOYntbZIsS5RuasABJKQQQVvAe50U1deIIqyQiwzQWYelMJ48WWpMQ==
Javascript outcome: 72ff8e7b653efbe3101d2c4ca7d7fe1af06652b907a90281aafa5ae09b45c9af091571b08d3d39cbad129939488319b2pprMQFFEJZR5JlrDsMqT8w==
The outcome should be Hello World
Both solutions work well within their own environment, however the C# or Javascript hashes can't be exchanged, they will not decrypt. My guess is that the character encoding has something to do with it, hence why the base64 sizes differ so much. Does anyone have a idea to get this working together? Thanks!
The error was in the Javascript code, the first part was Hex while the end was the encrypted result in Base64.
The following Javascript code makes the AES results interchangeable with the C# solution provided above. I had some difficulties making sure that all the results where properly encoded and decoded in Hex, so there are some new functions.
var keySize = 256;
var ivSize = 128;
var saltSize = 256;
var iterations = 1000;
var message = "Does this work?";
var password = "Secret Password";
function encrypt (msg, pass) {
var salt = CryptoJS.lib.WordArray.random(saltSize/8);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var iv = CryptoJS.lib.WordArray.random(ivSize/8);
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
var encryptedHex = base64ToHex(encrypted.toString());
var base64result = hexToBase64(salt + iv + encryptedHex);
return base64result;
}
function decrypt (transitmessage, pass) {
var hexResult = base64ToHex(transitmessage)
var salt = CryptoJS.enc.Hex.parse(hexResult.substr(0, 64));
var iv = CryptoJS.enc.Hex.parse(hexResult.substr(64, 32));
var encrypted = hexToBase64(hexResult.substring(96));
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
})
return decrypted.toString(CryptoJS.enc.Utf8);
}
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null,
str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
);
}
function base64ToHex(str) {
for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
var tmp = bin.charCodeAt(i).toString(16);
if (tmp.length === 1) tmp = "0" + tmp;
hex[hex.length] = tmp;
}
return hex.join("");
}
You are using Cipher Block Chaining (CBC) mode with a random IV (correct way).
Indirectly the IV will affect every plaintext block before the encryption.
Therefore comparing the content of the encrypted data will not help you here.
The length of the encrypted data is also different. I assume this is because the CryptoJS.lib.WordArray will be printed in hex.
Therefore You are getting seed and IV in hex encoding and the encrypted message in base64 encoding.
On C# side there is only one base64 encoded result containing everything.
In general plain CBC mode is no longer state-of-the-art encryption (e.g. for TLS1.3 alls ciphers with AES-CBC has been removed). Under certain conditions it may allows certain attacks (e.g. padding oracle attack). Therefore I would recommend to use an authenticating cipher mode like GCM mode instead.