node.js - Node crypto aes256-cbc 0x0 padding example -


From node crypto:

"Automatic blocking of input data to block you disabled If the auto-padding is incorrect, the length of the entire input data will be a multiple of the block size of the cipher or the final will be unsuccessful. It is useful for non-standard padding, eg using 0x0 instead of PKCS padding Last. "

It's all good, though, I could not find a suitable example anywhere:

Here are my thoughts:

function pad (str) {if ((str.length * 8)% 256! = 0) {str + = "0"; Pad (STR); }} Var str = "blah_blah_blah_blah_ asdf"; If (byte length and lieutenant; 256) {for (i = byte lang; i 256) {pad (str); }

It is not clearly ideal now because the cipher (method) method should remove the padding, although this will not happen, maybe I can pad it with hex instead of characters needed.

In addition, the modulus function fails on more than 256 strings shrug

The correct way to use custom padding (0x0) with node crypto What is it?

OK, after a little tinkering, I got the job of doing the full work.

Here's my code for those people who can find it useful:

  // me a utf8 encoded string function custom padding (str) {str = new Buffer ( Str, "UTF8") toString ("hex") .; Var bitLength = str.length * 8; If (bitLength & lt; 256) {for (i = bitLength; i & lt; 256; i + = 8) {str + = 0x0; }} And if (bit lang> 256) {while (str.length * 8)% 256! = 0) {str + = 0x0; }} Return to new buffer (str, "hex"). ToString ("utf8"); }  

You can use it in the following way:

  function encrypt (str) {var cipher = crypto.createCipheriv ('aes-256- Ccc ', key, iv) .setAutoPadding (wrong); Str = custom padding (str); Var crypt = cipher.update (str, 'utf8', 'base64'); Crypt + = cipher.final ("base64"); Return crypt; } Var t = encrypt ("friend");  

Comments