node crypto: en/decrypt token for validation - node.js

I want to en- and decrypt a token to be able to determine if it could be a valid token without accessing the DB.
My code is working for tokens that look "completely different" but if I only change one letter, a result is returned (no error thrown) thus looking like the token is valid ...!?
This is my code (plus changing the letter manually):
var crypto = require("crypto");
var cryptSecret = "a!=ksljdk34ajSDkl";
var token = "1d3889647173d415e24195ce5cafc36c1edcc053";
function _encodeUrlSaveBase64(str) {
return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, "");
}
function _decodeUrlSaveBase64(str) {
str = (str + "===").slice(0, str.length + (str.length % 4));
return str.replace(/-/g, "+").replace(/_/g, "/");
}
function _encrypt(data) {
var cipher = crypto.createCipher("aes256", cryptSecret);
var str = cipher.update(data, "utf8", "base64") + cipher.final("base64");
str = _encodeUrlSaveBase64(str);
return str;
}
function _decrypt(data) {
var str = _decodeUrlSaveBase64(data);
var decipher = crypto.createDecipher("aes256", cryptSecret);
str = decipher.update(str, "base64", "utf8") + decipher.final("utf8");
return str;
}
console.log("token: ", token);
var encrypted = _encrypt(token);
console.log("encrypted:", encrypted);
// change fourth letter to upper-case B (instead of lower-case)
encrypted = "bYzBYnU8FX7Rxs6Hae-yZkXvlwlRnhMQdLrT07e6YBy79nrK8FIpbKbxsYsXUmbk";
console.log("changed :", encrypted);
console.log("decrypt :", _decrypt(encrypted));
and it outputs:
token: 1d3889647173d415e24195ce5cafc36c1edcc053
encrypted: bYzbYnU8FX7Rxs6Hae-yZkXvlwlRnhMQdLrT07e6YBy79nrK8FIpbKbxsYsXUmbk
changed : bYzBYnU8FX7Rxs6Hae-yZkXvlwlRnhMQdLrT07e6YBy79nrK8FIpbKbxsYsXUmbk
decrypt : �g�
1��/b���e2.195ce5cafc36c1edcc053
where it should normally throw an error like this:
TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipher.Cipher.final (crypto.js:302:27)
at _decrypt (/***/test.js:25:59)
at Object.<anonymous> (/***/test.js:35:27)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:349:32)
at Function.Module._load (module.js:305:12)
at Function.Module.runMain (module.js:490:10)
at startup (node.js:123:16)
at node.js:1128:3
Am I doing anything wrong or is this just the way this works?

You need to distinguish between encryption (hide something) and signing (validate something). In your case you are hiding the content of the token. A simple solution for validating a token is a hash using a secret:
hashvalue = tokenvalue + hashfunction(tokenvalue + secret)
When validating, cut out the tokenvalue and calculate the hashvalue again, if it does not match someone must have tampered the token. A popular example of this is LTPA v1.
This scheme has some shortcomings, the biggest would be that every party needs the secret to validate the tokens and is therefore able to create a new valid token. IBM switched to public key for LTPA v2 because of this.

Related

Subtle Crypto Importing PCKS RSA Key leads to ERR_OSSL_ASN1_WRONG_TAG

I'm trying out the subtle crypto methods in Node.js 18. I want to import a private RSA Key.
I copied the example straight from the MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import) and rewrote it to be able to run it in Node.js:
const { subtle } = require('crypto').webcrypto;
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
// Example 2048 bit Key generated from https://travistidwell.com/jsencrypt/demo/
const pemEncodedKey = `-----BEGIN PRIVATE KEY-----
MIIEowIBAAKCAQBux5llZPW8B9b3n7lvw6wqeNUX/GKUB3iWN6FWWXRRlSdqvNkI2nGiiKE5lJv+ca507P/xPsj/ThmntnVPrwiN98FWlY8h7GPKAqPzzG+C+kOPpqvkZm10RHn/pjcdAi5QqBauMrZCis77x5O1ynJFu6DcDH/QM+0O4FCL+KHcahDhp/3Oc5O4cGDbGJcc8AsnD7d2Dv1yiFMDidKg2OuQIb/YvdxgO+DKB3Pjali3escD7b/Tj9iYQIhV3wEcXBFnenQGqz227bmtuRatyDgcOB5HL8k/YoxzTm7+1Qh2rhzJBe5zdZ86Ms7P7RPCg+od+wehzUowxWkxB372vWWfAgMBAAECggEAUxqRTKssXV5UOXctGVbk9QeodFH1ca8ZGzeoZKq+w+TsqPn6ptWYoaF1sUh2ra6CfVy9tDCxgDUKsfICl0BrXnUaKOYRdhVr1sOcUuxuSweLX1xdXv4n5izoiIwclDpqnD88pHmOmOSg2eiiOqIgj4dt6SXHTF1n3N0SD675XeuGmUVmNvw3V//FjpQqgAgVRsFoVI8rd3yxEeZRy/T8/lZWWQxt9232Ipcd91zHXFEvj+gQ8pAtyhLJ34dDJdT7Fs7eoDAkGqson1TedblGPbq+pieB59xGqciZgBQpcZNsfCuyzRA3skgd1Fu2NRnzgdDklKHnjEcUfib12nqTAQKBgQCyu77dAZezADejbCDxyRpHnGfp1Jz5p/Y/j9hvGEPl72aiFFZpD3Rbz3kPn9SayYVq5Zxjlt+KwuljNFppYeK0ZVZ2zWi1VmhrHwl+3yemf4ufltvCDCutDNLjjkt1rlwiz+eDmHSJiOFSEc5uJcFrwcAWDBKBQP1vn4VFqJ43fwKBgQCeq3tzAd/9W3ph7Dgv2ungimQ9vSZIfWawFnKyhfF5P7y8wJ6mgxnNv/BiuwqdqS5DY72EVq0tjwVvpHA6xCiWKYQ/9lhb9OJZsADbAaMRgKzuKCmpxJA2c6EKDQ2TK0/3WdLLnpuAXKcHP38sKJmKxm5wgRjC0pZLpWcK/xjh4QKBgQCEuxIxlAYxAz9OWHVauUqP1aIBr0fnywj/CPblAbMipZelU88b9EMoDzpLFRnQ3Uj8KonqF1fo93hUmMNvsSanav47+a0BxaqDqqfllRkf92Yb3O9T+q/Qsk5GeRymxxZbL+QxAN3CaWlTBjAz8kvilx7sAIkZfcb3xxI0udTNRwKBgD664SWI2jtaTToln9kbnVdOn27hNx91pIF9fn8iAWPEVSPyq0Z9klgLyEfgVsQaPNYburN1aSYX4zhONKinILytUUHQbQJ+AHcg5FWxgfzLeJL3gfFCaxl8AXDt1C4Y85aBBpvF6wiGmOp+qhKVQo7hAIyuHVH4276wd9qbHAVBAoGBAIqjXYfmtHRONXVtMCt5rlt3Y/Pe0KkA6vvfjGMnRKrmvEsHXh8Aj9ZPiTDxBKweJggg9BoJ/bs3juENIx5cJ76aiBYsdhw+4IGF79IfZm73k2ZC9exy9m69yp7GszmdZVJuiFlRoJFBMQm6oDH1+tUPW9M/76Ah8GpjkWx6dAcr
-----END PRIVATE KEY-----`;
const importPrivateKey = async () => {
const pemHeader = "-----BEGIN PRIVATE KEY-----";
const pemFooter = "-----END PRIVATE KEY-----";
const pemContents = pemEncodedKey.substring(pemHeader.length, pemEncodedKey.length - pemFooter.length);
const binaryDerString = Buffer.from(pemContents, 'base64').toString('binary');
const binaryDer = str2ab(binaryDerString);
const key = await subtle.importKey(
"pkcs8",
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["decrypt"]
);
}
importPrivateKey();
Now when I run this file, I get:
node:internal/crypto/keys:618
handle.init(kKeyTypePrivate, data, format, type, passphrase);
^
Error: error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag
at createPrivateKey (node:internal/crypto/keys:618:12)
at Object.rsaImportKey (node:internal/crypto/rsa:270:19)
at SubtleCrypto.importKey (node:internal/crypto/webcrypto:513:10)
at importPrivateKey (/Users/felix/Desktop/fts/js-api/bin/test.js:23:28)
at Object.<anonymous> (/Users/felix/Desktop/fts/js-api/bin/test.js:35:1)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Module._load (node:internal/modules/cjs/loader:827:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
opensslErrorStack: [
'error:0D08303A:asn1 encoding routines:asn1_template_noexp_d2i:nested asn1 error',
'error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error'
],
library: 'asn1 encoding routines',
function: 'asn1_check_tlen',
reason: 'wrong tag',
code: 'ERR_OSSL_ASN1_WRONG_TAG'
}
This example does work when I use the key from the linked MDN docs. But not if I use a freshly generated one.
What is going wrong here?
Your private key is inconsistent: You use the header and footer of a PKCS#8 key, but the body of a PKCS#1 formatted key. This can be verified e.g. in an ASN.1 parser like https://lapo.it/asn1js/.
Note that the JSEncrypt demo generates a PKCS#1 formatted private key (inclusive PKCS#1 header and footer).
Since WebCrypto API does not support PKCS#1 (see here), you need to convert the key to a PKCS8 formatted key, e.g. with OpenSSL.
Your key in PKCS#8 format (without line breaks in the body, so it can be used directly in JavaScript code) is:
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAG7HmWVk9bwH1vefuW/DrCp41Rf8YpQHeJY3oVZZdFGVJ2q82QjacaKIoTmUm/5xrnTs//E+yP9OGae2dU+vCI33wVaVjyHsY8oCo/PMb4L6Q4+mq+RmbXREef+mNx0CLlCoFq4ytkKKzvvHk7XKckW7oNwMf9Az7Q7gUIv4odxqEOGn/c5zk7hwYNsYlxzwCycPt3YO/XKIUwOJ0qDY65Ahv9i93GA74MoHc+NqWLd6xwPtv9OP2JhAiFXfARxcEWd6dAarPbbtua25Fq3IOBw4HkcvyT9ijHNObv7VCHauHMkF7nN1nzoyzs/tE8KD6h37B6HNSjDFaTEHfva9ZZ8CAwEAAQKCAQBTGpFMqyxdXlQ5dy0ZVuT1B6h0UfVxrxkbN6hkqr7D5Oyo+fqm1ZihoXWxSHatroJ9XL20MLGANQqx8gKXQGtedRoo5hF2FWvWw5xS7G5LB4tfXF1e/ifmLOiIjByUOmqcPzykeY6Y5KDZ6KI6oiCPh23pJcdMXWfc3RIPrvld64aZRWY2/DdX/8WOlCqACBVGwWhUjyt3fLER5lHL9Pz+VlZZDG33bfYilx33XMdcUS+P6BDykC3KEsnfh0Ml1PsWzt6gMCQaqyifVN51uUY9ur6mJ4Hn3EapyJmAFClxk2x8K7LNEDeySB3UW7Y1GfOB0OSUoeeMRxR+JvXaepMBAoGBALK7vt0Bl7MAN6NsIPHJGkecZ+nUnPmn9j+P2G8YQ+XvZqIUVmkPdFvPeQ+f1JrJhWrlnGOW34rC6WM0Wmlh4rRlVnbNaLVWaGsfCX7fJ6Z/i5+W28IMK60M0uOOS3WuXCLP54OYdImI4VIRzm4lwWvBwBYMEoFA/W+fhUWonjd/AoGBAJ6re3MB3/1bemHsOC/a6eCKZD29Jkh9ZrAWcrKF8Xk/vLzAnqaDGc2/8GK7Cp2pLkNjvYRWrS2PBW+kcDrEKJYphD/2WFv04lmwANsBoxGArO4oKanEkDZzoQoNDZMrT/dZ0suem4Bcpwc/fywomYrGbnCBGMLSlkulZwr/GOHhAoGBAIS7EjGUBjEDP05YdVq5So/VogGvR+fLCP8I9uUBsyKll6VTzxv0QygPOksVGdDdSPwqieoXV+j3eFSYw2+xJqdq/jv5rQHFqoOqp+WVGR/3Zhvc71P6r9CyTkZ5HKbHFlsv5DEA3cJpaVMGMDPyS+KXHuwAiRl9xvfHEjS51M1HAoGAPrrhJYjaO1pNOiWf2RudV06fbuE3H3WkgX1+fyIBY8RVI/KrRn2SWAvIR+BWxBo81hu6s3VpJhfjOE40qKcgvK1RQdBtAn4AdyDkVbGB/Mt4kveB8UJrGXwBcO3ULhjzloEGm8XrCIaY6n6qEpVCjuEAjK4dUfjbvrB32pscBUECgYEAiqNdh+a0dE41dW0wK3muW3dj897QqQDq+9+MYydEqua8SwdeHwCP1k+JMPEErB4mCCD0Ggn9uzeO4Q0jHlwnvpqIFix2HD7ggYXv0h9mbveTZkL17HL2br3KnsazOZ1lUm6IWVGgkUExCbqgMfX61Q9b0z/voCHwamORbHp0Bys=
-----END PRIVATE KEY-----
With this key format the JavaScript code works and the key is imported correctly.
By the way, under NodeJS you can use Buffer directly, i.e. the conversion via a binary string into an ArrayBuffer and thus also str2ab() are not needed:
...
const binaryDer = Buffer.from(pemContents, 'base64');
const key = await subtle.importKey(
"pkcs8",
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["decrypt"]
);
...
Note that even under v18.1.0, the WebCrypto API is marked Stability: 1 - Experimental (here).

How to decrypt a value in frontend which is encrypted in the backend (nodejs)?

Backend developers have encrypted a value in nodejs using crypto module. The code is shown below:
const _encrypt = async function(text){
var cipher = crypto.createCipher('aes-256-cbc','123|a123123123123123#&12')
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
console.log("in generic function....encrpted val", crypted)
return crypted;
}
I need to decrypt this value in the front end (Angular). So I tried decrypting like below:
let bytes = CryptoJS.AES.decrypt("e0912c26238f29604f5998fa1fbc78f6",'123|a123123123123123#&12');
if(bytes.toString()){
let m = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log("data ",m);
}
using hardcoded value. But Im getting Error: Malformed UTF-8 data error. Can anybody please tell me how to decrypt this in angular side?
This is a tricky enough one.. the crypto.createCipher function creates a key and IV from the password you provide (See the createCipher documentation for details).
This is implemented using the OpenSSL function EVP_BytesToKey.
A JavaScript implementation is available here: openssl-file.. we'll use this to get a key and IV from the password.
So there are two steps here:
Get a key and IV from your password.
Use these with Crypto.js to decode your encoded string.
Step 1: Get key and IV (Run in Node.js )
const EVP_BytesToKey = require('openssl-file').EVP_BytesToKey;
const result = EVP_BytesToKey(
'123|a123123123123123#&12',
null,
32,
'MD5',
16
);
console.log('key:', result.key.toString('hex'));
console.log('iv:', result.iv.toString('hex'));
Step 2: Decrypt string:
const encryptedValues = ['e0912c26238f29604f5998fa1fbc78f6', '0888e0558c3bce328cd7cda17e045769'];
// The results of putting the password '123|a123123123123123#&12' through EVP_BytesToKey
const key = '18bcd0b950de300fb873788958fde988fec9b478a936a3061575b16f79977d5b';
const IV = '2e11075e7b38fa20e192bc7089ccf32b';
for(let encrypted of encryptedValues) {
const decrypted = CryptoJS.AES.decrypt({ ciphertext: CryptoJS.enc.Hex.parse(encrypted) }, CryptoJS.enc.Hex.parse(key), {
iv: CryptoJS.enc.Hex.parse(IV),
mode: CryptoJS.mode.CBC
});
console.log('Ciphertext:', encrypted);
console.log('Plain text:', decrypted.toString(CryptoJS.enc.Utf8));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
Note that if you change the password you need to generate a new key and iv using EVP_BytesToKey.
I should note that createCipher is now deprecated, so use with caution. The same applies to EVP_BytesToKey.

How to decrypt cookie with nodejs

I am trying to make run this
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
//Raw cookie
var cookie = "B417B464CA63FE780584563D2DA4709B03F6195189044C26A29770F3203881DD90B1428139088D945CF6807CA408F201DABBADD59CE1D740F853A894692273F1CA83EC3F26493744E3D25D720374E03393F71E21BE2D96B6110CB7AC12E44447FFBD810D3D57FBACA8DF5249EB503C3DFD255692409F084650EFED205388DD8C08BF7B941E1AC1B3B70B9A8E09118D756BEAFF25834E72357FD40E80E76458091224FAE8";
//decryptionKey from issuers <machineKey>
var deckey = "FFA87B82D4A1BEAA15C06F6434A7EB2251976A838784E134900E6629B9F954B7";
var crypto = require('crypto');
var ivc = cookie, iv, cipherText, ivSize = 16, res = "";
ivc = new Buffer(ivc, 'hex');
iv = new Buffer(ivSize);
cipherText = new Buffer(ivc.length - ivSize);
ivc.copy(iv, 0, 0, ivSize);
ivc.copy(cipherText, 0, ivSize);
c = crypto.createDecipheriv('aes-256-cbc', hex2a(deckey), iv.toString('binary'));
res = c.update(cipherText, "binary", "utf8");
res += c.final('utf8');
console.log(res);
In this Q&A, it mentions about differences about node js versions, I tried that apply that one but with out success:
res = c.update(cipherText, "binary", "utf8");
line result such result
�sJ舸=�X7D������G����}x���T
and
res += c.final('utf8');
gives this error
0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
nodejs version: 4.1.2 and crypto version 0.0.3
How can I properly decrypt cookie with this algorith or can you suggest any other?
[Assuming you are trying to decrypt a .NET framework cookie]:
(Note: This answer was completely rewritten as things were not as simple as it seemed)
The encryption schema is described here, citing interesting parts:
VERIFY + DECRYPT DATA (fEncrypt = false, signData = true)
Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
Input (buf): E(iv + m + modifier) + HMAC(E(iv + m + modifier))
Output: m
The 'iv' in the above descriptions isn't an actual IV. Rather, if ivType = > IVType.Random, we'll prepend random bytes ('iv') to the plaintext before feeding it to the crypto algorithms. Introducing randomness early in the algorithm prevents users from inspecting two ciphertexts to see if the plaintexts are related. If ivType = IVType.None, then 'iv' is simply an empty string. If ivType = IVType.Hash, we use a non-keyed hash of the plaintext.
The 'modifier' in the above descriptions is a piece of metadata that should be encrypted along with the plaintext but which isn't actually part of the plaintext itself. It can be used for storing things like the user name for whom this plaintext was generated, the page that generated the plaintext, etc. On decryption, the modifier parameter is compared against the modifier stored in the crypto stream, and it is stripped from the message before the plaintext is returned.
Which is (hopefully) implemented with the following script:
// Input
var cookie = "B417B464CA63FE780584563D2DA4709B03F6195189044C26A29770F3203881DD90B1428139088D945CF6807CA408F201DABBADD59CE1D740F853A894692273F1CA83EC3F26493744E3D25D720374E03393F71E21BE2D96B6110CB7AC12E44447FFBD810D3D57FBACA8DF5249EB503C3DFD255692409F084650EFED205388DD8C08BF7B941E1AC1B3B70B9A8E09118D756BEAFF25834E72357FD40E80E76458091224FAE8";
var decryptionKey = "FFA87B82D4A1BEAA15C06F6434A7EB2251976A838784E134900E6629B9F954B7";
var validationKey = "A5326FFC9D3B74527AECE124D0B7BE5D85D58AFB12AAB3D76319B27EE57608A5A7BCAB5E34C7F1305ECE5AC78DB1FFEC0A9435C316884AB4C83D2008B533CFD9";
// Parameters
var hmacSize=20
// Make buffers for input
var cookieBuffer = new Buffer(cookie, 'hex');
var decryptionKeyBuffer = new Buffer(decryptionKey, 'hex');
var validationKeyBuffer = new Buffer(validationKey, 'hex');
// Parse cookie
var curOffset=0;
var cipherText = new Buffer(cookieBuffer.length - hmacSize);
curOffset+=cookieBuffer.copy(cipherText, 0, curOffset, curOffset+cipherText.length);
var hmac = new Buffer(hmacSize);
curOffset+=cookieBuffer.copy(hmac, 0, curOffset, curOffset+hmac.length);
// Verify HMAC
var crypto = require('crypto');
var h = crypto.createHmac('sha1', validationKeyBuffer);
h.update(cipherText);
var expectedHmac = h.digest();
console.log('Expected HMAC: ' + expectedHmac.toString('hex'));
console.log('Actual HMAC: ' + hmac.toString('hex'));
//if(!expectedHmac.equals(hmac)) { // Note: Requires nodejs v0.11.13
// throw 'Cookie integrity error';
//}
// Decrypt
var zeroIv = new Buffer("00000000000000000000000000000000", 'hex');
var c = crypto.createDecipheriv('aes-256-cbc', decryptionKeyBuffer, zeroIv);
var plaintext = Buffer.concat([c.update(cipherText), c.final()]);
// Strip IV (which is the same length as decryption key -- see notes below)
var res = new Buffer(plaintext.length-decryptionKeyBuffer.length);
plaintext.copy(res, 0, decryptionKeyBuffer.length, plaintext.length);
// Output
console.log('HEX: ' + res.toString('hex'));
console.log('UTF-8: ' + res.toString('utf8'));
Giving result:
Expected HMAC: 88e332b9a27b8f6f8d805ae718c562c1c8b721ed
Actual HMAC: 6beaff25834e72357fd40e80e76458091224fae8
HEX: 010112ea9a47b2f2ce08fe121e7d78b6f2ce0801085400650073007400550073006500720016540065007300740020007400650073007400730073006f006e002c00200072006f006c0066007a006f007200012f00ff1d892908d9c497bd804f5f22eab043ff6368702c
UTF-8: ��G���}x�TestUserTest testsson, rolfzor/���ė��O_"��C�chp,
Some (random) notes about this code:
it assumes that AES is used for encryption and HMAC-SHA1 is used for authentication
as the used authentication key is not known, the integrity check condition is commented out and verification key from this very related question is used (which is the reason for authentication tag mismatch)
the padding used for AES encryption is PKCS#7
the 'modifier' field is assumed empty. If this is not the case you would have to check it and remove it from the plaintext
for production environment you definitely should check the authentication tag (otherwise you would expose yourself to nasty attacks)
to avoid even nastier attacks, the authentication tag should be tested for equality in constant time (which might be tricky to implement in nodejs). Please note that the commented-out code is very probably vulnerable to timing-attacks.
the IV length is equal to the key length (see here for the reason)
Disclaimer: I did not study the original .NET code thoroughly, nor am I a crypto expert so please do validate my thoughts
Good luck!

Getting error "wrong final block length" when decrypting AES256 cipher

I'm facing exactly the same problem mentioned in this thread while encrypting and decrypting using AES.
crypto.js:202
var ret = this._handle.final();
^
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Error (native)
at Decipher.Cipher.final (crypto.js:202:26)
These are my encrypt and decrypt functions:
var config = {
cryptkey: crypto.createHash('sha256').update('Nixnogen').digest(),
iv: "a2xhcgAAAAAAAAAA"
};
function encryptText(text){
console.log(config.cryptkey);
var cipher = crypto.createCipheriv('aes-256-cbc', config.cryptkey, config.iv);
var crypted = cipher.update(text,'utf8','binary');
crypted += cipher.final('binary');
crypted = new Buffer(crypted, 'binary').toString('base64');
return crypted;
}
function decryptText(text){
console.log(config.cryptkey);
if (text === null || typeof text === 'undefined' || text === '') {return text;};
text = new Buffer(text, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-256-cbc', config.cryptkey, config.iv);
var dec = decipher.update(text,'binary','utf8');
dec += decipher.final('utf8');
return dec;
}
I've set "node": ">=0.10.0" in my package.json.
Can anyone tell me how to fix it? I have tried solutions mentioned in the thread but none of them are working for me.
Updates:
I've tried solutions mentioned in the thread but none of them are working for me. I think there might be a different solution for this and hence, rather than polluting the existing thread, decided to create a new one. Also, if I continue this on the existing thread it might confuse future candidates for the right solution.
Update 2:
For the second solution mentioned in the thread, I have the following code, but it is also giving me the same error:
function encryptText(text){
console.log(config.cryptkey);
var cipher = crypto.createCipheriv('aes-256-cbc', config.cryptkey, config.iv);
return Buffer.concat([
cipher.update(text),
cipher.final()
]);
}
function decryptText(text){
console.log(config.cryptkey);
if (text === null || typeof text === 'undefined' || text === '') {return text;};
var decipher = crypto.createDecipheriv('aes-256-cbc', config.cryptkey, config.iv);
return Buffer.concat([
decipher.update(text),
decipher.final()
]);
}
Also, I'm using these functions as getters and setters for a field in my mongodb database using mongoose. I don't think doing so will cause any issues, but I still thought it would be a good idea to mention this.
Update 3:
I'm trying to encrypt a Facebook access token and decrypt an encrypted Facebook access token.
To reproduce the error, you can try encrypting this token:
ASDFGHJKLO0cBACJDJoc25hkZAzcOfxhTBVpHRva4hnflYEwAHshZCi2qMihYXpS2fIDGsqAcAlfHLLo273OWImZAfo9TMYZCbuZABJkzPoo4HZA8HRJVCRACe6IunmBSMAEgGVv8KCLKIbL6Gf7HJy9PplEni2iJ06VoZBv0fKXUvkp1k7gWYMva1ZAyBsWiDiKChjq3Yh1ZCdWWEDRFGTHYJ
Encryption will work fine and you will get an encrypted string.
Now try decrypting the encrypted string which you got in the previous step. You will get the error.
This question is two years old at the time of this writing, but it has quite a few views, so I hope this answer will still prove useful to someone who might come across it.
The problem here is that encryptText works fine, but it's not returning a string. It's returning a Buffer. decryptText is expecting a string, not a Buffer, so it tries to read it as though it were a Buffer and you get the error that you received.
This is a simple fix. We just need to serialise the Buffer to a string when we encrypt text, and deserialise the encrypted string we receive when we decrypt text.
In this example, I use base64 encoding because it is fairly compact when representing binary data.
var config = {
cryptkey: crypto.createHash('sha256').update('Nixnogen').digest(),
iv: 'a2xhcgAAAAAAAAAA'
}
function encryptText (text) {
console.log(config.cryptkey)
var cipher = crypto.createCipheriv('aes-256-cbc', config.cryptkey, config.iv)
return Buffer.concat([
cipher.update(text),
cipher.final()
]).toString('base64') // Output base64 string
}
function decryptText (text) {
console.log(config.cryptkey)
if (text === null || typeof text === 'undefined' || text === '') {
return text
}
var decipher = crypto.createDecipheriv('aes-256-cbc', config.cryptkey, config.iv)
return Buffer.concat([
decipher.update(text, 'base64'), // Expect `text` to be a base64 string
decipher.final()
]).toString()
}
var encrypted = encryptText('text') // 8xXuS7jLG6crqJFHHB5J5A==
var decrypted = decryptText(encrypted) // text

Nodejs decrypt using crypto error wrong final block length

I use this code to crypt/decrypt string value
var crypto = require('crypto');
function encrypt(text){
var cipher = crypto.createCipher('aes-256-cbc','secret key');
var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
return encrypted;
}
function decrypt(text){
var decipher = crypto.createDecipher('aes-256-cbc','secret key');
var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
return decrypted ;
}
module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;
When i try to decrypt something that isn't crypted for example decrypt('test') it throw me the following error :
crypto.js:292
var ret = this._binding.final();
^
TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipher.Cipher.final (crypto.js:292:27)
I tryed also to use buffers without sucess and couldn't find any solution over Internet.
The real problem is I use this to decrypt cookie value. If a hacker creates a fake cookie with the value "test" it will crash my program.
The output of AES-CBC (without ciphertext stealing) is always a multiple of 16 bytes (32 hex characters). As you do not provide hexadecimal characters at all ("test") and since the string is not a multiple of 32 hexadecimal characters you will always see an error.
So this:
000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
would for instance be valid.
So you need to check that what you get is containing the right characters and is of the right length. To make sure that you don't get any padding or content related errors you will need to put a (hexadecimal encoded) HMAC value calculated over the ciphertext at the end. Then first check encoding, length and then the HMAC. If the HMAC is correct you can be assured that the plaintext won't contain any invalid information after decryption.
I also faced the same issue. I had to go through all the comments to check for answer and #Alexey Ten's comment helped me. So in order to make #Alexey Ten's answer more visible below are the changes.
var crypto = require('crypto');
function encrypt(text){
try{
var cipher = crypto.createCipher('aes-256-cbc','secret key');
var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
return encrypted;
} catch(exception) {
throw exception;
}
}
function decrypt(text){
try{
var decipher = crypto.createDecipher('aes-256-cbc','secret key');
var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
return decrypted ;
} catch(exception) {
throw exception;
}
}

Resources