Question

I want to create two functions encrypt(message, key) and decrypt(ciphertext, key) using the Forge library in javascript, but I dont undestand the example code.

// generate a random key and IV
var key = forge.random.getBytesSync(16);
var iv = forge.random.getBytesSync(16);

// encrypt some bytes using CBC mode
// (other modes include: CFB, OFB, and CTR)
var cipher = forge.aes.createEncryptionCipher(key, 'CBC');
cipher.start(iv);
cipher.update(forge.util.createBuffer(someBytes));
cipher.finish();
var encrypted = cipher.output;
// outputs encrypted hex
console.log(encrypted.toHex());

// decrypt some bytes using CBC mode
// (other modes include: CFB, OFB, and CTR)
var cipher = forge.aes.createDecryptionCipher(key, 'CBC');
cipher.start(iv);
cipher.update(encrypted);
cipher.finish();
// outputs decrypted hex
console.log(cipher.output.toHex());

// generate a password-based 16-byte key
var salt = forge.random.getBytesSync(128);
var derivedKey = forge.pkcs5.pbkdf2('password', salt, numIterations, 16);

Where should I use my own key? Where can I choose 256 bit mode? Can you give me an easier example?

Was it helpful?

Solution

Where should I use my own key?

I haven't used that library but it seems pretty straight forward. Take this part at the top:

// generate a random key and IV
var key = forge.random.getBytesSync(16);

And put your key in like this:

// generate a random key and IV
var key = neverGuessMahKeyIs1234;

Do the same for the iv if you want.


Where can I choose 256 bit mode?

Ok, so first of all your dealing with symmetric encryption which has a key length of the desired size. Because it's symmetric, it's used on both the encrypting and decrypting ends, which is what the code that you posted seems to do. I say 'seems' because I'm trusting that the library's native functions are as you posted them. So, the code as you posted seems to use (as I showed above) 128 bits (16*8=128). If you want a random 256, then just use:

var key = forge.random.getBytesSync(32);

Or just make your own key that 256 bits long.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top