I'm using node forge to encrypt a form before sending it to the server using AES.
The code for the crypto part for now is
const bigInt = require("big-integer");
const forge = require('node-forge');
function generateParams() {
// Cryptographic random number generator
var array = new Uint32Array(2);
var _key = bigInt(window.crypto.getRandomValues(array)[0]).toString();
var _iv = bigInt(window.crypto.getRandomValues(array)[1]).toString();
// generate random key and IV
var key = forge.util.encode64(_key);
var iv = forge.util.encode64(_iv);
const params = {
key: key,
iv: iv
}
return params;
}
function encrypt(params) {
var cipher = forge.rc2.createEncryptionCipher(params.key);
cipher.start(params.iv);
// Encrypting "testing"
cipher.update(forge.util.createBuffer("testing"));
cipher.finish();
return cipher.output;
}
function decrypt(params, encrypted) {
var cipher = forge.rc2.createDecryptionCipher(params.key);
cipher.start(params.iv);
cipher.update(encrypted);
cipher.finish();
return cipher.output;
}
and the jQuery function is (not posting yet)
$('#recordForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Grab form data
// Crypto
const params = generateParams();
const encryptedForm = {
test: encrypt(params),
}
console.log("Encrypted: " + encryptedForm.test);
const decryptedForm = {
test: decrypt(params, encryptedForm.id).data,
}
console.log("Decrypted: " + decryptedForm.test);
});
My problem is that I keep getting back (cryptob.js is the name of my file, generated with browserify)
Uncaught URIError: URI malformed
at decodeURIComponent (<anonymous>)
at Object.util.decodeUtf8 (cryptob.js:24437)
at ByteStringBuffer.util.ByteStringBuffer.toString (cryptob.js:23490)
at HTMLFormElement.<anonymous> (cryptob.js:1282)
at HTMLFormElement.dispatch (jquery-3.1.1.slim.min.js:3)
at HTMLFormElement.q.handle (jquery-3.1.1.slim.min.js:3)
when calling encrypt().
There is this answer here which recommends including a special meta tag. I have done that but it still doesn't work. Since some resources online say it is related to UTF-8 encoding, I tried replacing
cipher.update(forge.util.createBuffer("testing"));
with
cipher.update(forge.util.createBuffer(encodeURIComponent("testing")));
or
cipher.update(forge.util.createBuffer("testing", 'utf8'));
but it didn't work either (based on encodeURIComponent(str)).
You can test forge here, and if you run this code (which is essentially what I'm doing)
var forge = require("node-forge")
// generate a random key and IV
var key = forge.util.encode64("12354523465");
var iv = forge.util.encode64("2315");
// encrypt some bytes
var cipher = forge.rc2.createEncryptionCipher(key);
cipher.start(iv);
cipher.update(forge.util.createBuffer("testing"));
cipher.finish();
var encrypted = cipher.output;
console.log(encrypted);
// decrypt some bytes
var cipher = forge.rc2.createDecryptionCipher(key);
cipher.start(iv);
cipher.update(encrypted);
cipher.finish();
console.log(cipher.output.data)
it works fine.
How can I solve this?
It looks like this error is actually happening in the toString, where you generate your _key and _iv.
Try testing with some hard-coded strings, as used in the example code you posted. Then, use a method to generate random byte strings for the key and IV.
Also, for AES-256, the key should have 32 bytes (not bits) of entropy. The IV should have 16 bytes of entropy.
I am using the below code to encrypt strings in my node.js code.
I would like to understand how to generate KEY and HMAC_KEY from a static source. In my program, it's generated randomly as of now. As it's generated randomly, I am not able to encrypt my database password using the below algorithm.
crypto = require('crypto');
ALGORITHM = "AES-256-CBC";
HMAC_ALGORITHM = "SHA256";
KEY = crypto.randomBytes(32);
HMAC_KEY = crypto.randomBytes(32);
function (plain_text) {
var IV = new Buffer(crypto.randomBytes(16)); // ensure that the IV (initialization vector) is random
var cipher_text;
var hmac;
var encryptor;
encryptor = crypto.createCipheriv(ALGORITHM, KEY, IV);
encryptor.setEncoding('hex');
encryptor.write(plain_text);
encryptor.end();
cipher_text = encryptor.read();
hmac = crypto.createHmac(HMAC_ALGORITHM, HMAC_KEY);
hmac.update(cipher_text);
hmac.update(IV.toString('hex')); // ensure that both the IV and the cipher-text is protected by the HMAC
// The IV isn't a secret so it can be stored along side everything else
return cipher_text + "$" + IV.toString('hex') + "$" + hmac.digest('hex')
};
You have to split your code into two executions:
Code that generates your keys and presents them in a storable format
KEY = crypto.randomBytes(32);
HMAC_KEY = crypto.randomBytes(32);
console.log(KEY.toString('hex'));
console.log(HMAC_KEY.toString('hex'));
Code that uses the stored keys
KEY = Buffer.from('some key string', 'hex');
HMAC_KEY = Buffer.from('some other key string', 'hex');
You just have to make sure that your keys aren't actually in your code, but rather in some file, because hardcoding key in code and checking them into your version control system is a bad idea and might give your developers access to production systems which they probably shouldn't have.
So I have my iOS code:
#import <CommonCrypto/CommonCrypto.h>
NSString* password = #"1234567890123456";
NSString* salt = #"gettingsaltyfoo!";
-(NSString *)decrypt:(NSString*)encrypted64{
NSMutableData* hash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
NSMutableData* key = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CC_SHA256(salt.UTF8String, (CC_LONG)strlen(salt.UTF8String), hash.mutableBytes);
CCKeyDerivationPBKDF(kCCPBKDF2, password.UTF8String, strlen(password.UTF8String), hash.bytes, hash.length, kCCPRFHmacAlgSHA1, 1000, key.mutableBytes, key.length);
NSLog(#"Hash : %#",[hash base64EncodedStringWithOptions:0]);
NSLog(#"Key : %#",[key base64EncodedStringWithOptions:0]);
NSData* encryptedWithout64 = [[NSData alloc] initWithBase64EncodedString:encrypted64 options:0];
NSMutableData* decrypted = [NSMutableData dataWithLength:encryptedWithout64.length + kCCBlockSizeAES128];
size_t bytesDecrypted = 0;
CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
NULL,
encryptedWithout64.bytes, encryptedWithout64.length,
decrypted.mutableBytes, decrypted.length, &bytesDecrypted);
NSData* outputMessage = [NSMutableData dataWithBytes:decrypted.mutableBytes length:bytesDecrypted];
NSString* outputString = [[NSString alloc] initWithData:outputMessage encoding:NSUTF8StringEncoding];
NSLog(#"Decrypted : %#",outputString);
return outputString;
}
-(NSString *)encrypt:(NSString *)toEncrypt{
NSMutableData* hash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
NSMutableData* key = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CC_SHA256(salt.UTF8String, (CC_LONG)strlen(salt.UTF8String), hash.mutableBytes);
CCKeyDerivationPBKDF(kCCPBKDF2, password.UTF8String, strlen(password.UTF8String), hash.bytes, hash.length, kCCPRFHmacAlgSHA1, 1000, key.mutableBytes, key.length);
NSData* message = [toEncrypt dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData* encrypted = [NSMutableData dataWithLength:message.length + kCCBlockSizeAES128];
size_t bytesEncrypted = 0;
CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
NULL,
message.bytes, message.length,
encrypted.mutableBytes, encrypted.length, &bytesEncrypted);
NSString* encrypted64 = [[NSMutableData dataWithBytes:encrypted.mutableBytes length:bytesEncrypted] base64EncodedStringWithOptions:0];
NSLog(#"Encrypted : %#",encrypted64);
return encrypted64;
}
and I have my node.js code:
var CryptoJS = require("crypto-js");
var crypto = require('crypto');
var password = "1234567890123456";
var salt = "gettingsaltyfoo!";
var hash = CryptoJS.SHA256(salt);
var key = CryptoJS.PBKDF2(password, hash, { keySize: 256/32, iterations: 1000 });
var algorithm = 'aes128';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,key.toString(CryptoJS.enc.Base64));
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
console.log(crypted);
console.log(hash.toString(CryptoJS.enc.Base64));
console.log(key.toString(CryptoJS.enc.Base64));
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,key.toString(CryptoJS.enc.Base64));
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
console.log(dec);
return dec;
}
Question: Unfortunately, though I have the same hash, key, and eventually decrypted value (meaning they can work independently), I get different encrypted values. So in one code, if I take the encrypted value and try to decrypt it in another, I get an error. When I go from iOS to node I get this error:
ERROR:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length CODE: decrypt('vfOzya0yV9G5hLHeSh3R1g==');
Also I get these different encrypted values for the string "Hello World":
IOS: vfOzya0yV9G5hLHeSh3R1g==
NODE: 13b51a6785f47d8601c3a612d41b9a8b
How can I resolve this matter so that I can interop my iOS and Node.js, and in the future Android. I know my hashing algorithm is right for producing the SHA256 and PBDKF2 because I get the same hash and key. This means that somewhere my implementation is wrong for AES128 upon encrypting my password. Most likely my iOS code. Please let me know where my error is.
You don't need to use CryptoJS, because node.js' crypto module provides everything you need for this to work. CryptoJS has a different binary representation than node.js' native Buffer, so there will be problem using both in conjunction.
Problems:
You're using crypto.createCipher() which will derive the key from a password on its own in an OpenSSL compatible format. You want to use crypto.createCipheriv().
You're not passing an IV to in Objective-C which defaults to a zero filled IV. You need to do the same in node.js by initializing a zero-filled Buffer.
You provide the key in Base64 encoded form in node.js, but you have to provide the bytes (Buffer).
Since the key size is 256 bit you're actually using AES-256 and not AES-128. The CommonCrypto code seems to change automatically to 256 bit despite specifying 128 bit, but node.js requires you to specify 256 bit explicitly. Also, "aes128" or "aes256" will default to ECB mode in node.js, but CommonCrypto defaults to CBC mode, so you need to explicitly specify this.
Full working code:
var crypto = require('crypto');
var password = "1234567890123456";
var salt = "gettingsaltyfoo!";
var sha256 = crypto.createHash("sha256");
sha256.update(salt);
var hash = sha256.digest();
var key = crypto.pbkdf2Sync(password, hash, 1000, 32, "sha1");
var iv = new Buffer(16);
iv.fill(0);
var algorithm = 'aes-256-cbc';
function encrypt(text){
var cipher = crypto.createCipheriv(algorithm, key, iv);
var crypted = cipher.update(text,'utf8','base64');
crypted += cipher.final('base64');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipheriv(algorithm, key, iv);
var dec = decipher.update(text,'base64','utf8');
dec += decipher.final('utf8');
return dec;
}
console.log(encrypt("Hello World"));
Output:
vfOzya0yV9G5hLHeSh3R1g==
Other considerations:
You need to generate a random IV for every encryption that you do. If you don't do this, then an attacker may see that you encrypted the same message multiple times without actually decrypting it if you use the same key every time. Since you derive a key from a password, then you can do this a bit better by generating a random salt and derive 384 bit (48 byte) from PBKDF2. Use the first 32 byte for the key and the rest for the IV.
You need to authenticate the ciphertexts. If you don't then an attacker might mount a padding oracle attack on your system. You can easily do this by running an HMAC over the ciphertext and send the resulting tag along with it. You can then verify the tag before decryption by running the HMAC again over the received ciphertext in order to check for manipulation.
Or you could use an authenticated mode like GCM.
For a given project, I'm looking to encrypt a piece of data with AES 256, and then RSA encrypt the key. I've been using Forge and the Encryptor gem in ruby, and i can't seem get matching encryption values:
var key = 'strengthstrengthstrengthstrength';
var iv = 'cakecakecakecakecakecakecakecake';
var cipher = forge.aes.createEncryptionCipher(key, 'CBC');
cipher.start(iv);
cipher.update(forge.util.createBuffer("some string"));
cipher.finish();
var encrypted = cipher.output;
console.log(btoa(encrypted.data)); // outputs: CjLmWObDO2Dlwa5tJnRBRw==
Then in IRB:
Encryptor.encrypt 'some string', :key => 'strengthstrengthstrengthstrength', :key => 'cakecakecakecakecakecakecakecake'
Base64.encode64 _
# outputs: C9Gtk9YfciVMJEsbhZrQTw==\n
Over using string values for Key & IV, tried:
var key = forge.random.getBytesSync(32);
var iv = forge.random.getBytesSync(32);
Then doing a btoa() call on each of them. Using the Base64.decode64 on the ruby side, before passing them to Encryptor.decrypt, but still no luck.
Any idea where i've gone wrong?
I managed to get it to work. Since i'm just using one key to encrypt one value, i just used the key as the IV & Salt as well. This is not recommended if you are using the key to encrypt multiple values. You will then need to generate proper salt & iv values.
Also the gen key value is a pretty poor way, as Math.random is not secure. Just ran out of time to do this properly, but works okay for this case.
var Encryption = (function () {
var api = {
getKey: function () {
var possible = "ABCDEFabcdef0123456789";
var key = '';
for (var i = 0; i < 32; i++) {
key += possible.charAt(Math.floor(Math.random() * possible.length));
}
return key;
},
encryptPII: function (rawKey, value) {
var salt = rawKey;
var iv = rawKey;
var key = forge.pkcs5.pbkdf2(rawKey, salt, 2000, 32);
var cipher = forge.aes.createEncryptionCipher(key, 'CBC');
cipher.start(iv);
cipher.update(forge.util.createBuffer(value));
cipher.finish();
return btoa(cipher.output.data);
}
};
return api;
})();
The rawKey is the value returned from getKey(). The value property is the the string to be encrypted. I use the rawkey for iv & salt values, generate a key in the same way that the Encryptor gem in ruby does. Use forge to then encrypt the string value.
If i take the base64, decode it in ruby, and pass the same rawKey value to the encryptor gem for key, salt and iv, it works.
I'm working with a project that currently is doing encryption in a salesforce apex class (using the Crypto library) and that logic needs to be moved into a javascript file. The node.js package I'm trying to use to do the encryption is node-rsa.
Here's the code that currently exists in apex:
String algName = 'RSA';
blob signature;
String signGen = '';
String pKey = 'MIIEvgIBADANBgkqhkiG<rest of key snipped>';
String payload = 'some payload';
blob privateKey = EncodingUtil.base64Decode(pKey);
blob input = Blob.valueOf(payload);
signature = Crypto.sign(algName, input, privateKey);
signGen = EncodingUtil.base64Encode(signature);
And here's the initial javascript implementation:
var tmp = forge.util.decode64(pKey);
var privateKey2 = new NodeRSA(tmp);
payload = 'some payload
var encrypted = key.encrypt(payload, 'base64');
The problem I'm having is that the line:
var privateKey2 = new NodeRSA(tmp);
is causing the following error:
Invalid PEM format
The private key that the node-rsa uses in their example has markets at the beginning and end of the key of:
---- BEGIN RSA PRIVATE KEY -----
---- END RSA PRIVATE KEY -----
So I'm not sure if I have to somehow indicate to the node-rsa library that this key is in a different format. Or maybe there's another RSA javascript library I could try using?
I left you a response for how to do this using forge here: https://github.com/digitalbazaar/forge/issues/150
var pkey = 'some base64-encoded private key';
var pkeyDer = forge.util.decode64(pkey);
var pkeyAsn1 = forge.asn1.fromDer(pkeyDer);
var privateKey = forge.pki.privateKeyFromAsn1(pkeyAsn1);
// above could be simplified if pkey is stored in standard PEM format, then just do this:
// var pkey = 'some private key in pem format';
// var privateKey = forge.pki.privateKeyFromPem(pkey);
var payload = 'some string payload';
var md = forge.md.sha1.create();
md.update(payload, 'utf8');
var signature = privateKey.sign(md);
var signature64 = forge.util.encode64(signature);
// signature64 is now a base64-encoded RSA signature on a SHA-1 digest
// using PKCS#1v1.5 padding... see the examples for other padding options if necessary