I need to decrypt incoming requests encrypted with AES, I try to use shared example and unable to find right set of parameters
Encryption:AES/CBC/PKCS5Padding AES/CBC/PKCS5
Initialization vector: emptybyte array which length is 16
Test secret key:1234567890123456
Plain text: abcdefghigklmnopqrstuvwxyz0123456789
Encrypted: 8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr
I use next
const cryptkey = '1234567890123456';
const cleardata = "abcdefghigklmnopqrstuvwxyz0123456789";
const crypted = "8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr";
var decrypt = CryptoJS.AES.decrypt(crypted, cryptkey, {
iv: CryptoJS.enc.Hex.parse('0000000000000000'),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var ddd = decrypt.toString(CryptoJS.enc.Utf8);
console.log(ddd);
Every time I am getting empty string.
Where do I fail?
------ UPDATE -----
New version with applied comments, still does not work
const cryptkey = CryptoJS.enc.Utf8.parse('1234567890123456');
const crypted = CryptoJS.enc.Base64.parse("8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr");
var decrypt = CryptoJS.AES.decrypt(crypted, cryptkey, {
iv: CryptoJS.enc.Hex.parse('00000000000000000000000000000000'),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
You would have to parse the UTF-8 key first:
const cryptkey = CryptoJS.enc.Utf8.parse('1234567890123456');
If you don't do that CryptoJS will assume it is a password and derive the actual key from that.
As Maarten also pointed out...
The ciphertext also must be decoded from Base64:
const crypted = CryptoJS.enc.Base64.parse("8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr");
Note that the decryptor expects a CipherParams object, which you can simulate by passing {ciphertext: crypted} to the decrypt function. Alternatively, you can rely on CryptoJS to decode the ciphertext from Base64, you pass in that string as-is.
The IV must be 16 bytes long for AES-CBC which are 32 characters if encoded as Hex:
CryptoJS.enc.Hex.parse('00000000000000000000000000000000')
Examples
const cryptkey = CryptoJS.enc.Utf8.parse('1234567890123456');
const crypted = CryptoJS.enc.Base64.parse("8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr");
var decrypt = CryptoJS.AES.decrypt({ciphertext: crypted}, cryptkey, {
iv: CryptoJS.enc.Hex.parse('00000000000000000000000000000000'),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log(decrypt.toString(CryptoJS.enc.Utf8));
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
As Matt correctly noted, CryptoJS can do the ciphertext decoding for you if the ciphertext is encoded as Base64:
const cryptkey = CryptoJS.enc.Utf8.parse('1234567890123456');
const crypted = "8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr";
var decrypt = CryptoJS.AES.decrypt(crypted, cryptkey, {
iv: CryptoJS.enc.Hex.parse('00000000000000000000000000000000'),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log(decrypt.toString(CryptoJS.enc.Utf8));
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
Security considerations:
The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.
A key should be randomly chosen from all possible bytes, because a key consisting of ASCII characters is much easier to brute-force than a key consisting of all available bytes.
It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.
If you're using only symmetric encryption you need the exact same key at the server and the client. If you send the encryption key from the server to the client or the other way around you need to encrypt your symmetric encryption key. The easiest way to do this would be to use TLS. If you use TLS, then the data as well as key are encrypted, so you don't need to encrypt it yourself. This doesn't provide any security, just a little bit of obfuscation. You should read: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/
You are forgetting to base 64 decode the ciphertext in crypted (I guess you'd have to use atob() to do that). Your IV is too small as well, hexadecimals take two hex digits per byte.
This work for me, using enc and not only UTF8
const { AES, enc } = require('crypto-js')
const { decrypt, encrypt } = AES
const message = "Hi my friend"
const messageEncrypt = "oPVu8Dd8ERPIAWr+7rQzIQ=="
const key= "key123456"
const aesDecrypt = decrypt(messageEncrypt,key).toString(enc.Utf8)
console.log(aesDecrypt) // Hi my friend
Related
I want to decrypt a string that has been encrypted with openssl on the server like this:
openssl enc -e -aes-256-cbc -pbkdf2 -a -S 0123456789ABCDEF -A -k mypassword
Note this is done providing only a salt and password, and openssl should handle key and IV automatically. Am I too optimistic that this can happen when the browser decrypts too? If at all possible, I want to do it with only those encryption settings, or the bare minimum of increased complexity. In the browser, I'm trying to decrypt with CryptoJS like this:
import * as CryptoJS from 'crypto-js'
const encrypted = <ENCRYPTED_STRING_FROM_SERVER>
const password = 'mypassword'
const salt = '0123456789ABCDEF'
const key = CryptoJS.PBKDF2(password, salt) // Generate key
const bytes = CryptoJS.AES.decrypt(encrypted, key)
const decrypted = bytes.toString(CryptoJS.enc.Utf8)
console.log(decrypted)
But the call to CryptoJS.AES.decrypt errors with Cannot read property '0' of undefined, crypto-js/cipher-core.js:371. The docs for CryptoJS.AES.decrypt are quite thin, and any settings I am aware of to change when calling that func seem to give the same error. Thanks to anyone who can shine light!
In the OpenSSL statement, the iteration count and digest are not specified, so the default values 10000 and SHA256 are used. This is relevant because CryptoJS uses different default values (1 and SHA1).
CryptoJS applies the OpenSSL format for the ciphertext, i.e. the encrypted data starts with the ASCII encoding of Salted__ followed by the salt and then the ciphertext. Therefore the beginning of the Base64 encoded ciphertext starts always with U2FsdGVkX1.
CryptoJS uses the WordArray data type, which encapsulates an array of words. A word consists of 4 bytes.
During decryption, ciphertext and salt must first be separated. Then, key and IV must be determined using PBKDF2. Due to the different default values, iteration count and digest must be specified explicitly. Finally it can be decrypted:
// 1. Separate ciphertext and salt
var encrypted = "U2FsdGVkX18BI0VniavN78vlhR6fryIan0VvUrdIr+YeLkDYhO2xyA+/oVXJj/c35swVVkCqHPh9VdRbNQG6NQ=="
var encryptedWA = CryptoJS.enc.Base64.parse(encrypted);
var prefixWA = CryptoJS.lib.WordArray.create(encryptedWA.words.slice(0, 8/4)); // Salted__ prefix
var saltWA = CryptoJS.lib.WordArray.create(encryptedWA.words.slice(8/4, 16/4)); // 8 bytes salt: 0x0123456789ABCDEF
var ciphertextWA = CryptoJS.lib.WordArray.create(encryptedWA.words.slice(16/4, encryptedWA.words.length)); // ciphertext
// 2. Determine key and IV using PBKDF2
var password = 'mypassword'
var keyIvWA = CryptoJS.PBKDF2(
password,
saltWA,
{
keySize: (32+16)/4, // key and IV
iterations: 10000,
hasher: CryptoJS.algo.SHA256
}
);
var keyWA = CryptoJS.lib.WordArray.create(keyIvWA.words.slice(0, 32/4));
var ivWA = CryptoJS.lib.WordArray.create(keyIvWA.words.slice(32/4, (32+16)/4));
// 3. Decrypt
var decryptedWA = CryptoJS.AES.decrypt(
{ciphertext: ciphertextWA},
keyWA,
{iv: ivWA}
);
var decrypted = decryptedWA.toString(CryptoJS.enc.Utf8)
console.log(decrypted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
More details can be found in the CryptoJS documentation.
try this lib in browser
https://www.npmjs.com/package/cryptojs2
More details can be found in the documentation.
Below AES ECB javascript code is giving the output, but while testing it in online tool it gives padding issue "final block not padded properly,bad key is used" .Is there any way to solve this issue in javascript please suggest
var encrypted = CryptoJS.AES.encrypt("Test","HhiiAlLHowRYoU69", {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("encryptByAES ciphertext: "+encrypted);
var decrypted = CryptoJS.AES.decrypt(encrypted,"HhiiAlLHowRYoU69", {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("decryptByAES plaintext: "+decrypted);
OUTPUT OF THE ABOVE CODE
encryptByAES ciphertext: U2FsdGVkX1+heFB5M+220TMdq12Q22/zuSNXXMJg4+0=
decryptByAES plaintext: Test
const key = CryptoJS.enc.Utf8.parse("HhiiAlLHowRYoU69");
var encrypted = CryptoJS.AES.encrypt(msg,key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("Encrypted data ="+encrypted);
var decrypted = CryptoJS.AES.decrypt(encrypted,key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var decryptedText = decrypted.toString( CryptoJS.enc.Utf8 );
console.log( "decrypted Text = " + decryptedText );
This is the working solution i got to my above posted problem in javascript.
CryptoJS decides to interpret your "key" as a password if you pass it a string. Then it derives a key from that password - which is quite different from that password.
For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key. If you pass the actual key, you must also pass the actual IV.
That's also why your ciphertext is so large: it contains an 8 byte salt and the ciphertext. The salt is combined with the password to derive the key. The salt is preceded with a string / magic Salted__, try and view your ciphertext in a hex editor, and you'll find that the 8 first bytes are not all that random.
An AES key should consist of fully unpredictable bits / bytes. That means that a printable string cannot be a key, because it leaves unprintable characters out by definition. If you want to use a specific test key, define one using hexadecimals and use Hex.parse from the CryptoJS library.
ECB is insecure, you should use an authenticated mode like GCM.
I need to encrypt a chat message that will be stored a database. The data is a string of characters of various lengths. I want to use the native node.js crypto library and use a symmetric encryption protocol such as AES 256. I have concerns are the following:
Is CBC the correct AES mode for this use case for this type of field stored in a TEXT field in MySQL?
Does the key look like it is generated correctly?
Is the IV correct? Is prepending the IV to the encrypted text a proper way to do it or should it be a separate field?
// AES RFC - https://tools.ietf.org/html/rfc3602
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
// generate key with crypto.randomBytes(256/8).toString('hex')
const key = '6d858102402dbbeb0f9bb711e3d13a1229684792db4940db0d0e71c08ca602e1';
const IV_LENGTH = 16;
const encrypt = (text) => {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};
const decrypt = (text) => {
const [iv, encryptedText] = text.split(':').map(part => Buffer.from(part, 'hex'));
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
exports.encrypt = encrypt;
exports.decrypt = decrypt;
Is CBC the correct AES mode for this use case for this type of field stored in a TEXT field in MySQL?
Well, this depends a bit on your text. But probably yes.
Does the key look like it is generated correctly?
yeah, looks good to me. It should look random and it looks random. Not sure what your concern is here.
Is the IV correct? Is prepending the IV to the encrypted text a proper way to do it or should it be a separate field?
The IV looks good to me. I don't see many reasons why you shouldn't do it this way except one: its not very storage efficient. It would be far more efficient to store the data not as hex string but as binary data! And then you can't just use a colon to seperate the data. So either you know that its the first n bytes or you do a seperate field. Both has upsides and downsides, but both is ok. It's primary a question about style.
I am using CryptoJS to manually decrypt a string with a provided set of values. The secret is provided and then an SHA256 has is taken of it. The message and initialization vector are base 64 encoded. Here's what I am trying, but every time I run it, the output changes - how can that be?! I'm at the end of my wits...
// Key and take the hash of it
var secretKey = 'TESTING123Secret_Key';
var secretKeyHash = CryptoJS.SHA256(secretKey).toString(CryptoJS.enc.Hex);
// Base 64 encoded values
var accountNumberBase64 = 'nxjYfo4Stw63YBEcnjo3oQ==';
var initializationVectorBase64 = 'HnNcvu9AP9yl09APWkWnDQ==';
// decode the values provided above
var accountNumberEncrypt = atob(accountNumberBase64);
var initializationVector = atob(initializationVectorBase64);
// Use crypto to decrypt
var decrypted = CryptoJS.AES.decrypt(
{
ciphertext: accountNumberEncrypt,
salt: ''
},
secretKeyHash,
{
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding,
iv: initializationVector,
salt: ''
}
);
console.log(' decrypted, by hand: ' + decrypted.toString(CryptoJS.enc.Hex));
the last line changes every time this is run (run it on page load) - same values provided every time, output is different.
How it is supposed to work:
Decryption Instructions:
1. A static, secret key will be shared which will be used for decryption (Secret Key TBD).
a. HASH the secret key with SHA256, encode it to Hex and use the first 32 characters. This will be used as the KEY when decrypting.
2. Two pieces of information will be sent via the POST method
a. Parameter “AN”: A Base64 Encoded, AES-256-CBC Encrypted string which will represent the Account Number when decrypted
b. Parameter “IV”: A Base64 Encoded initialization vector (IV) string which will be used in decrypting the Account Number string
3. Base64 Decode both parameters
4. Using the AES-256-CBC method, decrypt the encrypted string (which was base64 decoded as part of Step #3) with the initialization vector decoded in Step #3 and the hash created in Step #1a
5. The decryption should then provide you the account number.
Java code
There many issues with your code. It is hard to say what is really responsible for the non-deterministic decryption. I guess it is the fact that you're passing the key as a string which means that CryptoJS will assume that it is a password and try to use EVP_BytesToKey to derive a key from that. Since the salt is not set, CryptoJS probably has a bug that it generates a random salt for decryption (which it should not). You need to parse the key into a WordArray if you want to manually provide the key.
The other main issue is using non-CryptoJS methods for decoding (atob) which means that you get some data format that cannot be directly read by CryptoJS. CryptoJS relies on the internal WordArray for representing all binary data or expects all strings to be UTF-8-encoded.
Working code:
// Key and take the hash of it
var secretKey = 'TESTING123Secret_Key';
var secretKeyHash = CryptoJS.SHA256(secretKey).toString(CryptoJS.enc.Hex).slice(0,32);
secretKeyHash = CryptoJS.enc.Utf8.parse(secretKeyHash);
// Base 64 encoded values
var accountNumberBase64 = 'nxjYfo4Stw63YBEcnjo3oQ==';
var initializationVectorBase64 = 'HnNcvu9AP9yl09APWkWnDQ==';
var ct = CryptoJS.enc.Base64.parse(accountNumberBase64);
var iv = CryptoJS.enc.Base64.parse(initializationVectorBase64);
// Use crypto to decrypt
var decrypted = CryptoJS.AES.decrypt({
ciphertext: ct
},
secretKeyHash, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding,
iv: iv
}
);
console.log(' decrypted, by hand: ' + decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/sha256.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/components/pad-nopadding-min.js"></script>
In communication between two applications, I'd like to encrypt a piece of information in JavaScript and decrypt the message from an Objective-C client using a fixed key (just for basic security).
Encryption works well:
var command = "mjallo";
var crypto_key = CryptoJS.enc.Base64.parse('280f8bb8c43d532f389ef0e2a5321220');
var crypto_iv = CryptoJS.enc.Base64.parse("CC0A69779E15780A");
// Encrypt and encode
var encrypted = CryptoJS.AES.encrypt(command, crypto_key, {iv: crypto_iv}).toString();
var encrypted_and_encoded = btoa(encrypted);
// encrypted_and_encoded => 'dFBQVDZZS3dGSktoa0J3Y1NQOElpZz09'
// Confirms that decrypt works with CryptoJS:
// Decode and decrypt
var decrypted = CryptoJS.AES.decrypt(atob(encrypted_and_encoded), crypto_key, {iv: crypto_iv});
// decrypted => 'mjallo'
How would you go about decoding and decrypting the message in Objective-c after it was encrypted by CryptoJS?
I've attempted to decrypt using CocoaSecurity, but with no luck. Following is RubyMotion syntax:
begin
res = CocoaSecurity.aesDecryptWithBase64('dFBQVDZZS3dGSktoa0J3Y1NQOElpZz09', hexKey: '280f8bb8c43d532f389ef0e2a5321220', hexIv: 'CC0A69779E15780A')
rescue NSException => e
p e.reason # => "Length of iv is wrong. Length of iv should be 16(128bits)"
end
AES supports a block size of 128 bit and key sizes of 128, 192 and 256 bit. The IV for CBC mode (which is the default) should be 128 bit.
Your encoded key consists of 32 characters. In CryptoJS you're parsing it as Base64 which results in a 192 bit key, but in CocoaSecurity you're assuming that it is Hex encoded. Since it only contains digits and the letters a to f, it's likely Hex encoded and not Base64 encoded. If one would assume that it is Hex encoded, then one would get a valid AES key size of 128 bit:
var crypto_key = CryptoJS.enc.Hex.parse('280f8bb8c43d532f389ef0e2a5321220');
Your IV on the other hand doesn't have a valid size under the same assumption. An IV should be 16 bytes long for AES in CBC mode. Additionally, an IV should never be fixed at a static value. You would need to generate a random IV for every encryption. Since the IV doesn't have to be secret, you can send it along with the ciphertext.
var crypto_iv = CryptoJS.lib.WordArray.random(128/8);
console.log("IV: " + crypto_iv.toString()); // hex encoded
The result of CryptoJS.<Cipher>.encrypt() is a special formattable object. If you call toString() on that object, you will get a Base64 encoded ciphertext (optionally with a salt when password-based encryption was used). But then you're encoding it again with Base64 by calling btoa(). You don't need to encode it twice.
var encrypted = CryptoJS.AES.encrypt(command, crypto_key, {iv: crypto_iv}).toString();
console.log("Ciphertext (Base64): " + encrypted.toString());
console.log("Ciphertext (Hex): " + encrypted.ciphertext.toString());
As far I can judge, your RubyMotion code looks fine.
If you can only change the CocoaSecurity code, then you will need to
re-encode the key by decoding it as Base64 and encoding it as Hex,
append 16 "0" characters to the IV hex string, because CryptoJS fills the IV up to the next valid IV with 0x00 bytes,
decode the ciphertext once from Base64.
You should always authenticate the ciphertexts. This can either be done with an authenticated mode like GCM or with an HMAC over the ciphertext.