digitalbazaar / forge

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps
https://digitalbazaar.com/
Other
5.04k stars 778 forks source link

How to save key and iv in a database for later use? #315

Closed Dindaleon closed 8 years ago

Dindaleon commented 8 years ago

Hello,

I need to save the key and iv in a database for later use. Both are generated the following way: var secret = forge.random.getBytesSync(32); var iv = forge.random.getBytesSync(32);

The problem is that if I save them just like that, and then retrieve them, they get corrupted. So, what is the proper way for storing and retrieving those values?

EDIT I am saving them like this:

var secretHex = forge.util.bytesToHex(secret);
var ivHex = forge.util.bytesToHex(iv);

Then, when I need to decipher, I convert them back to bytes like this:

var secretBytes = forge.util.hexToBytes(secretHex);
var ivBytes = forge.util.hexToBytes(ivHex);
var somedataBytes = forge.util.hexToBytes(somedataHex);

var decipher = forge.cipher.createDecipher('AES-CBC', secretBytes);
decipher.start({ iv: ivBytes });
decipher.update(somedataBytes);
decipher.finish();
console.log('outputs decrypted hex ', decipher.output.toHex());

This gives me the following error:

error TypeError: buffer.getBytes is not a function
at ByteStringBuffer.util.ByteStringBuffer.putBuffer (C:\NodeServer\hapi-react-starter-kit\hapi-react-starter-kit\node_modules\node-forge\js\util.js:391:31)
at [object Object].BlockCipher.update (C:\NodeServer\hapi-react-starter-kit\hapi-react-starter-kit\node_modules\node-forge\js\cipher.js:170:17)
dlongley commented 8 years ago

Wrap your bytes in a forge buffer:

decipher.update(forge.util.createBuffer(somedataBytes));
Dindaleon commented 8 years ago

@dlongley great! That fixed it.

Another question, in this issue (https://github.com/digitalbazaar/forge/issues/135) you say to use at most 16 bytes for the IV. Could you please elaborate more on this? Can the key size be 32 bytes and the IV size only 16? Right now, I am setting both to 32.

dlongley commented 8 years ago

@Dindaleon,

The IV size needs to match the block size for the cipher, not the key size. AES uses a 16 byte block size and hence a 16 byte IV. It doesn't matter what the key size is, the IV is always 16 bytes. AES-128 uses a 16 byte key and 16 byte IV, AES-192 uses a 24 byte key and a 16 byte IV, AES-256 uses a 32 byte key and a 16 byte IV.

If you provide an IV of 32 bytes, the last 16 bytes will be ignored. So just use 16 bytes so there won't be any confusion.

Dindaleon commented 8 years ago

Perfect! Thank you.

erlangparasu commented 5 years ago

Thank you so much sir @dlongley :+1:

TheGEN1U5 commented 3 years ago

Wrap your bytes in a forge buffer:

decipher.update(forge.util.createBuffer(somedataBytes));

I don't know how to thank you!!! It worked!