I'm trying to decrypt an AES-256-CBC ciphertext from a web service using Node.js but can't seem to make it work and honestly lost.
const raw = `{
"iv":"uUwGJgxslfYiahji3+e2jA==",
"docMimeType":"text\/xml",
"doc":"1XLjWZlMMrgcpR6QtfwExQSOOPag1BJZTo1QEkcDrY6PFesWoVw8xrbHFsEYyMVDeemzk+5kBnb3\r\nqBmcUtkSFs7zDsxjYZkkEU9nyq1jXFz99fGylIealw37FPMaK0gviXESRO5AHMs46tpgSQcuWX0Z\r\nV7+mnTvjmaRHi4p1Cvg8aYfDO1aIWWWjAwOTCyopyCwribbGoEdiYDc5pERHpw=="
}`;
const cleanedEncryptedDataAsJsonStr = raw.replace(/\r?\n|\r/g, " ")
const data = JSON.parse(cleanedEncryptedDataAsJsonStr)
const ivBase64 = data.iv
const iv = Buffer.from(ivBase64, 'base64').toString('hex').substring(0, 16)
const plainKey = 'PHilheaLthDuMmyciPHerKeyS'
const hashKey = crypto.createHash('sha256');
hashKey.update(plainKey)
const key = hashKey.digest('hex').substring(0, 32)
let encrypted = Buffer.from(data.doc, 'base64').toString('hex')
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
let decrypted = decipher.update(encrypted, 'hex', 'utf-8')
decrypted += decipher.final('utf-8')
so I'm receiving a json object which contains the iv and the encrypted data(doc), and I have a copy of the cipher key which according to the docs needs to be hashed during the decryption.
doc: base64 encoding of the encrypted data
iv: base64 encoded value of initialization vector during encryption
When I run my code, the error is:
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
and also not sure on how to handle \r\n in the raw json string.
The decrypted message should be:
<eEMPLOYERS ASOF="07-02-2022"><employer pPEN="110474000002" pEmployerName="JOSE A TERAMOTO ODM" pEmployerAddress="ORANBO, PASIG CITY"/></eEMPLOYERS
There are the following issues in the code:
IV and key must not be hex encoded.
The default PKCS#7 padding must be disabled since Zero padding was applied during encryption (if desired, explicitly remove the trailing 0x00 padding bytes).
Fixed code:
var crypto = require('crypto')
const raw = `{
"iv":"uUwGJgxslfYiahji3+e2jA==",
"docMimeType":"text\/xml",
"doc":"1XLjWZlMMrgcpR6QtfwExQSOOPag1BJZTo1QEkcDrY6PFesWoVw8xrbHFsEYyMVDeemzk+5kBnb3\r\nqBmcUtkSFs7zDsxjYZkkEU9nyq1jXFz99fGylIealw37FPMaK0gviXESRO5AHMs46tpgSQcuWX0Z\r\nV7+mnTvjmaRHi4p1Cvg8aYfDO1aIWWWjAwOTCyopyCwribbGoEdiYDc5pERHpw=="
}`;
const cleanedEncryptedDataAsJsonStr = raw.replace(/\r?\n|\r/g, " ")
const data = JSON.parse(cleanedEncryptedDataAsJsonStr)
const ivBase64 = data.iv
const iv = Buffer.from(ivBase64, 'base64') // .toString('hex').substring(0, 16) // Fix 1: no hex encoding
const plainKey = 'PHilheaLthDuMmyciPHerKeyS'
const hashKey = crypto.createHash('sha256')
hashKey.update(plainKey)
const key = hashKey.digest() // .digest('hex').substring(0, 32) // Fix 2: no hex encoding
let encrypted = Buffer.from(data.doc, 'base64').toString('hex')
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
decipher.setAutoPadding(false) // Fix 3: disable default PKCS#7 padding
let decrypted = decipher.update(encrypted, 'hex', 'utf-8')
decrypted += decipher.final('utf-8')
console.log(decrypted) // plaintext zero-padded, if necessary remove trailing 0x00 values, e.g. as in the following:
console.log(decrypted.replace(new RegExp("\0+$"), "")) // <eEMPLOYERS ESOF="07-02-2022"><employer pPEN="110474000002" pEmployerName="JOSE A TERAMOTO ODM" pEmployerAddress="ORANBO, PASIG CITY"/></eEMPLOYERS>
Related
I'm trying to port the following Go functions to nodeJS using crypt or crypt-js but i'm having issues trying to figure out what's wrong:
The Go encryption code is available at https://go.dev/play/p/O88Bslwd-qh ( both encrypt and decrypt work)
The current nodejs implementation is:
var decryptKey= "93D87FF936DAB334C2B3CC771C9DC833B517920683C63971AA36EBC3F2A83C24";
const crypto = require('crypto');
const algorithm = 'aes-256-cfb';
const BLOCK_SIZE = 16;
var message = "8a0f6b165236391ac081f5c614265b280f84df882fb6ee14dd8b0f7020962fdd"
function encryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
//Decode hex key
keyStr = Buffer.from(keyStr, "hex")
hash.update(keyStr);
const keyBytes = hash.digest();
const iv = crypto.randomBytes(BLOCK_SIZE);
const cipher = crypto.createCipheriv(algorithm, keyBytes, iv);
cipher.setAutoPadding(true);
let enc = [iv, cipher.update(text,'latin1')];
enc.push(cipher.final());
return Buffer.concat(enc).toString('hex');
}
function decryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
//Decode hex key
keyStr = Buffer.from(keyStr, "hex")
hash.update(keyStr);
const keyBytes = hash.digest();
const contents = Buffer.from(text, 'hex');
const iv = contents.slice(0, BLOCK_SIZE);
const textBytes = contents.slice(BLOCK_SIZE);
const decipher = crypto.createDecipheriv(algorithm, keyBytes, iv);
decipher.setAutoPadding(true);
let res = decipher.update(textBytes,'latin1');
res += decipher.final('latin1');
return res;
}
console.log(message)
result = decryptText(decryptKey,message);
console.log(result);
message = encryptText(decryptKey,'hola').toString();
console.log(message)
result = decryptText(decryptKey,message);
console.log(result);
Any idea why it is not working as expected?
Note: I know that padding is not required with cfb but i can't modify the encryption code, it just for reference.
I don't know Go or the specifics of aes.NewCipher(key), but from its documentation it doesn't look like it's hashing the key in any way. The Go code you're linking to also doesn't hash it, so I'm not sure why you're hashing it in the Node.js code.
This should be sufficient:
function encryptText(keyStr, text) {
const keyBytes = Buffer.from(keyStr, "hex")
…
}
function decryptText(keyStr, text) {
const keyBytes = Buffer.from(keyStr, 'hex');
…
}
As an aside: it looks like you may be encrypting JSON blocks with these functions. If so, I would suggest not using any encoding (like latin1) during the encryption/decryption process, given that JSON text must be encoded using UTF-8.
I am getting an error when decrypting a response using crypto that i don't understand Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
I'm decrypting a response that looks like this 'p6\u001e�s�p>l?a%ޟ�=~m�\u0002D�K(�[<\u0007O�6\u001c�a�[sP�=\u00112\u001d�)n�Ⴓ?, i've shortened it for brevity. The end result is that it should be a JSON object
My code is as follows
const crypto = require('crypto');
const secret = "mysecret";
const algorithm = 'aes-128-cbc';
function decryptAES(message) {
const bytes = Buffer.from(message);
const salt = bytes.slice(bytes.length - 8);
const key = crypto.pbkdf2Sync(secret, salt, 10000, 16, 'sha1');
const iv = bytes.slice(bytes.length - 24, bytes.length - 8);
const data = bytes.slice(0, bytes.length - 24);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrpyted = decipher.update(data, 'hex', 'utf8');
decrpyted = Buffer.concat([decrpyted, decipher.final('utf8')])
console.log(decrpyted.toString());
}
What could I be doing wrong and what does the error message mean?
Update
From looking at how the data is encrypted the other side I can see that they are using PKCS7Padding. In my decryption code I am not specifying this. Can this be done with crypto?
I tried using aes256,aes-cross, and crypto.
But I was not able to decrypt the key which is encrypted using AES 256 (aes-256-ecb) with PKCS7 padding.
I ended up with the following mentioned errors.
Error: Invalid key length
at Decipheriv.createCipherBase
(or)
Error: Invalid IV length
at Decipheriv.createCipherBase
I was not able to find an npm package that helps me.
Here is the sample code:
const crypto = require("crypto");
//Length of my key is 32
const key = Buffer.from("aaaaaabbbbbbccccccddddddssssssaa", "base64");
//_sek is the encrypted key
const _sek = "NEPkEuWaXZUawBHJZIcMjHJeKuPkaQezuRc3bjWEezlbHzmqCSyh2hazB+WeAJaU"
const cipher = crypto.createDecipheriv(
"aes-256-ecb",
Buffer.from(key, "base64"),
Buffer.from([])
);
return cipher.update(_sek, "base64", "utf8") + cipher.final("utf8");
If anyone could help me with a code-based example in nodejs. It will help me to understand clearly.
Update:
function decrypt(encryted_key, access_key) {
var key = Buffer.from(access_key, "base64");
const decipher = crypto.createDecipheriv("aes-256-ecb", key, "");
decipher.setAutoPadding(false);
var decryptedSecret = decipher.update(encryted_key, "utf8", "base64");
decryptedSecret += decipher.final("base64");
return decryptedSecret;
}
decrypt(
"w2lI56OJ+RqQ04PZb5Ii6cLTxW2bemiMBTXpIlkau5xbmhwP4Qk3oyIydKV1ttWa",
"DvpMLxqKlsdhKe9Pce+dqTdNUnrofuOQPsgmSHhpxF8="
)
Required output: "cdgLxoHvpeMoMd3eXISoMcgQFRxZeMSez5x3F2YVGT4="
But got this : "G7z/eXQefnaeB7mYBq7KDrH+R4LtauNi6AU1v0/yObqoOidSOkIeW085DiMxdCDDjaI+hJiS2JRHDL1fdLrveg="
Thanks in advance.
The Invalid key length error is caused when the length of the key doesn't match the specified algorithm. E.g. in the posted code aes-256-ecb is specified, which defines AES-256, i.e. AES with a key length of 32 bytes. However, the key used has a length of only 24 bytes, since it's Base64 decoded when it's read into the buffer. This means that either a 32 bytes key must be used (e.g. if UTF-8 is used as encoding instead of Base64 when reading into the buffer), or AES-192 (specified as aes-192-ecb).
The Invalid IV length error is caused when an IV is specified in ECB mode (which doesn't use an IV at all), or when in a mode which uses an IV, its length doesn't match the blocksize of the algorithm (e.g. 16 bytes for AES). Since the ECB mode is used here, simply pass null for the IV (Buffer.from([]) works too).
Example using AES-192 and a 24 bytes key:
const crypto = require("crypto");
const key = "aaaaaabbbbbbccccccddddddssssssaa";
const secret = "01234567890123456789012345678901";
// Encryption
const cipher = crypto.createCipheriv("aes-192-ecb", Buffer.from(key, "base64"), null);
const encryptedSecret = cipher.update(secret, "utf8", "base64") + cipher.final("base64");
console.log(encryptedSecret);
// Decryption
const decipher = crypto.createDecipheriv("aes-192-ecb", Buffer.from(key, "base64"), null);
const decryptedSecret = decipher.update(encryptedSecret, "base64", "utf8") + decipher.final("utf8");
console.log(decryptedSecret);
During decryption, UTF-8 is used as output encoding which is of course only possible if the plaintext is compatible with this, otherwise a suitable encoding such as Base64 has to be applied.
Code Sample is as follows:
var crypto = require('crypto');
var key = 'ExchangePasswordPasswordExchange';
var plaintext = '150.01';
var iv = new Buffer(crypto.randomBytes(16))
ivstring = iv.toString('hex');
var cipher = crypto.createCipheriv('aes-256-cbc', key, ivstring)
var decipher = crypto.createDecipheriv('aes-256-cbc', key,ivstring);
cipher.update(plaintext, 'utf8', 'base64');
var encryptedPassword = cipher.final('base64');
Getting error of invalid IV length.
From https://github.com/nodejs/node/issues/6696#issuecomment-218575039 -
The default string encoding used by the crypto module changed in
v6.0.0 from binary to utf8. So your binary string is being interpreted
as utf8 and is most likely becoming larger than 16 bytes during that
conversion process (rather than smaller than 16 bytes) due to invalid
utf8 character bytes being added.
Modifying your code so that ivstring is always 16 characters in length should solve your issue.
var ivstring = iv.toString('hex').slice(0, 16);
The above answer adds more overhead than needed, since you converted each byte to a hexidecimal representation that requires twice as many bytes all you need to do is generate half the number of bytes
var crypto = require('crypto');
var key = 'ExchangePasswordPasswordExchange';
var plaintext = '150.01';
var iv = new Buffer(crypto.randomBytes(8))
ivstring = iv.toString('hex');
var cipher = crypto.createCipheriv('aes-256-cbc', key, ivstring)
var decipher = crypto.createDecipheriv('aes-256-cbc', key,ivstring);
cipher.update(plaintext, 'utf8', 'base64');
var encryptedPassword = cipher.final('base64');
In Node.js 10 I had to use a 12 bytes string for it to work... const iv = crypto.pseudoRandomBytes(6).toString('hex');. 16 bytes gave me an error. I had this problem when I was running Node.js 10 globally, and then uploading it to a Cloud Functions server with Node.js 8. Since Cloud Functions have Node.js 10 in beta, I just switched to that and now it works with the 12 bytes string. It didn't even work with a 16 bytes string on Node.js 8 on the Cloud Functions server...
When you really need Key/Iv from legacy Crypto
In case of cypher aes-256-cbc, required length for Key and IV is 32 Bytes and 16 Bytes.
You can calculate Key length by dividing 256 bits by 8 bits, equals 32 bytes.
Following GetUnsafeKeyIvSync(password) uses exactly same behavior as previous crypto did in old days.
There is no salt, and single iteration with MD5 digest, so anyone can generate exactly same Key and Iv.
This is why deprecated.
However, you may still need to use this approach only if your encrypted data is stored and cannot be changed(or upgraded.).
Do NOT use this function for new project.
This is provided only for who cannot upgrade previously encrypted data for other reason.
import * as crypto from 'node:crypto';
import { Buffer } from 'node:buffer';
export function GetUnsafeKeyIvSync(password) {
try {
const key1hash = crypto.createHash('MD5').update(password, 'utf8');
const key2hash = crypto.createHash('MD5').update(key1hash.copy().digest('binary') + password, 'binary');
const ivhash = crypto.createHash('MD5').update(key2hash.copy().digest('binary') + password, 'binary');
const Key = Buffer.from(key1hash.digest('hex') + key2hash.digest('hex'), 'hex');
const IV = Buffer.from(ivhash.digest('hex'), 'hex');
return { Key, IV };
}
catch (error) {
console.error(error);
}
}
export function DecryptSync(data, KeyIv) {
let decrypted;
try {
const decipher = crypto.createDecipheriv('aes-256-cbc', KeyIv.Key, KeyIv.IV);
decrypted = decipher.update(data, 'hex', 'utf8');
decrypted += decipher.final('utf8');
}
catch (error) {
console.error(error);
decrypted = '';
}
return decrypted;
}
export function EncryptSync(data, KeyIv) {
let encrypted;
try {
const cipher = crypto.createCipheriv('aes-256-cbc', KeyIv.Key, KeyIv.IV);
encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
}
catch (error) {
console.error(error);
encrypted = '';
}
return encrypted;
}
For testing,
export function Test() {
const password = 'my plain text password which is free from length requirment';
const data = 'this is data to be encrypted and decrypted';
// Use same logic to retrieve as legacy crypto did.
// It is unsafe because there is no salt and single iteration.
// Anyone can generate exactly same Key/Iv with the same password.
// We would only need to use this only if stored encrypted data must be decrypted from previous result.
// Do NOT use this for new project.
const KeyIv = GetUnsafeKeyIvSync(password);
// Key is in binary format, for human reading, converted to hex, but Hex string is not passed to Cypher.
// Length of Key is 32 bytes, for aes-256-cbc
console.log(`Key=${KeyIv.Key.toString('hex')}`);
// Key is in binary format , for human reading, converted to hex, but Hex string is not passed to Cypher.
// Length of IV is 16 bytes, for aes-256-cbc
console.log(`IV=${KeyIv.IV.toString('hex')}`);
const encrypted = EncryptSync(data, KeyIv);
console.log(`enc=${encrypted}`);
const decrypted = DecryptSync(encrypted, KeyIv);
console.log(`dec=${decrypted}`);
console.log(`Equals ${decrypted === data}`);
return decrypted === data;
}
I'm trying to implement encrypt/decrypt functions using aes-128-gcm as provided by node crypto. From my understanding, gcm encrypts the ciphertext but also hashes it and provides this as an 'authentication tag'. However, I keep getting the error: "Unsupported state or unable to authenticate data".
I'm not sure if this is an error in my code - looking at the encrypted ciphertext and auth tag, the one being fetched by the decrypt function is the same as the one produced by the encrypt function.
function encrypt(plaintext) {
// IV is being generated for each encryption
var iv = crypto.randomBytes(12),
cipher = crypto.createCipheriv(aes,key,iv),
encryptedData = cipher.update(plaintext),
tag;
// Cipher.final has been called, so no more encryption/updates can take place
encryptedData += cipher.final();
// Auth tag must be generated after cipher.final()
tag = cipher.getAuthTag();
return encryptedData + "$$" + tag.toString('hex') + "$$" + iv.toString('hex');
}
function decrypt(ciphertext) {
var cipherSplit = ciphertext.split("$$"),
text = cipherSplit[0],
tag = Buffer.from(cipherSplit[1], 'hex'),
iv = Buffer.from(cipherSplit[2], 'hex'),
decipher = crypto.createDecipheriv(aes,key,iv);
decipher.setAuthTag(tag);
var decryptedData = decipher.update(text);
decryptedData += decipher.final();
}
The error is being thrown by decipher.final().
In case if someone still tries to get a working example of encryption and decryption process.
I've left some comments that should be taken into consideration.
import * as crypto from 'crypto';
const textToEncode = 'some secret text'; // utf-8
const algo = 'aes-128-gcm';
// Key bytes length depends on algorithm being used:
// 'aes-128-gcm' = 16 bytes
// 'aes-192-gcm' = 24 bytes
// 'aes-256-gcm' = 32 bytes
const key = crypto.randomBytes(16);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algo, key, iv);
const encrypted = Buffer.concat([
cipher.update(Buffer.from(textToEncode, 'utf-8')),
cipher.final(),
]);
const authTag = cipher.getAuthTag();
console.info('Value encrypted', {
valueToEncrypt: textToEncode,
encryptedValue: encrypted.toString('hex'),
authTag: authTag.toString('hex'),
});
// It's important to use the same authTag and IV that were used during encoding
const decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(authTag);
const decrypted = Buffer.concat([
decipher.update(encrypted),
decipher.final(),
]);
console.info('Value decrypted', {
valueToDecrypt: encrypted.toString('hex'),
decryptedValue: decrypted.toString('utf-8'),
});
I managed to fix this: the issue was that I wasn't specifying an encoding type for cipher.final() and I was returning it within a String, so it wasn't returning a Buffer object, which decipher.final() was expecting.
To fix, I add 'utf-8' to 'hex' encoding parameters within my cipher.update and cipher.final, and vice versa in decipher.
Edited to add code example - note this is from 2018, so may be outdated now.
function encrypt(plaintext) {
// IV is being generated for each encryption
var iv = crypto.randomBytes(12),
cipher = crypto.createCipheriv(aes,key,iv),
encryptedData = cipher.update(plaintext, 'utf-8', 'hex'),
tag;
// Cipher.final has been called, so no more encryption/updates can take place
encryptedData += cipher.final('hex');
// Auth tag must be generated after cipher.final()
tag = cipher.getAuthTag();
return encryptedData + "$$" + tag.toString('hex') + "$$" + iv.toString('hex');
}
function decrypt(ciphertext) {
var cipherSplit = ciphertext.split("$$"),
text = cipherSplit[0],
tag = Buffer.from(cipherSplit[1], 'hex'),
iv = Buffer.from(cipherSplit[2], 'hex'),
decipher = crypto.createDecipheriv(aes, key, iv);
decipher.setAuthTag(tag);
var decryptedData = decipher.update(text, 'hex', 'utf-8');
decryptedData += decipher.final('utf-8');
}