Node decrypt content with private key and padding - node.js

So, I have a content which needs to be decrypted with private key and padding AES/ECB/PKCS5Padding.
I tried many libraries, and many examples, but none of them works. Now, this is the one where I managed to finish to the last steps, but im not sure if there is another library that can do this for me.
var absolutePath = path.resolve('./private.txt');
var privateKey = fs.readFileSync(absolutePath, "utf8");
var buffer = new Buffer(toDecrypt, "base64");
var decrypted = crypto.privateDecrypt(privateKey, buffer);
return decrypted.toString("utf8");
This one throws me error:
0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
The second example, slighlty different than the first one, but uses padding (thats what I need, I just wanted to try without it to see if it works):
var stringKey = 'BEGIN RSA PRIVATE KEY-----....';
var cipherText = 'ENCRYPTEDTEXT';
// we compute the sha256 of the key
var hash = crypto.createHash("sha256");
hash.update(stringKey, "utf8");
var sha256key = hash.digest();
var keyBuffer = new Buffer(sha256key);
var cipherBuffer = new Buffer(cipherText, 'hex');
var aesDec = crypto.createDecipheriv("aes-256-ecb", keyBuffer, ''); // always use createDecipheriv when the key is passed as raw bytes
var output = aesDec.update(cipherBuffer, 'binary', 'binary');
var final = aesDec.final();
return output + final;
It crashes on the line var final = aesDec.final() and throws error:
digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
Does anybody has knowledge or expirience on how to do this?

We had similar issue.
We receieved encrypted base 64 string from api and needed to decrypt aes key, and then, with decrypted aes key, we needed to decrypt the payload.
What we have done:
var bytes = new Buffer(input, 'base64'); this is the encrypted data from server
var aes = bytes.slice(offset, offset + AES_SIZE); slice byte array to get aes
`var aesString = aes.toString('binary');` convert it to binary string
Use forge library:
var forge = require('node-forge');
var pki = require('node-forge').pki;
// Grab private key from file
var absolutePath = path.resolve('../private-key.txt');
var privateKey = fs.readFileSync(absolutePath, "utf8");
// Generate private key object
var private_key = pki.privateKeyFromPem(privateKey);
var result;
// Decrypt aes key with private key
try {
result = private_key.decrypt(api.apiSecret, 'RSA-OAEP', {
md: forge.md.sha1.create(),
mgf1: {
md: forge.md.sha1.create()
}
});
} catch (err) {
console.error(err.message);
return;
}
// Build byte array from aes key
var base = new Buffer(result, 'binary');
// Generate initialization vector
var iv = forge.random.getBytesSync(api.content.length);
// Create decipher object with AES/ECB/PKCS5 padding
var decipher = forge.cipher.createDecipher('AES-ECB', forge.util.createBuffer(base));
decipher.start({ iv: iv });
// Add content for decrypting
decipher.update(forge.util.createBuffer(api.content));
var result = decipher.finish();
// Get json data from decipher object
var data = decipher.output.data;

Related

generate encrypted signature with private key

Good afternoon I would like to generate an encrypted signature of a string with my private key (pem) in nodejs but it marks the following: TypeError: Passphrase required for encrypted key
firma = `||${transferecias.institucionContraparte}|${transferecias.Empresa}||`;
console.log(firma);
var absolutePath = path.resolve('ruta\certs\\prueba-key.pem');
var publicKey = fs.readFileSync(absolutePath, "utf8");
var buffer = new Buffer(firma);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
console.log(encrypted);

Is there a vulnerability if the beginning of the plaintext is known before encryption?

Assuming this is my encrypt and decrypt function using native crypto from node.js.
var algo = 'aes-256-cbc';
var algoSecret = 'mySecret';
var encrypt = function(secret){
var cipher = require('crypto').createCipher(algo,algoSecret);
var crypted = cipher.update(secret,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
var decrypt = function(text){
var decipher = require('crypto').createDecipher(algo,algoSecret);
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
return dec;
}
I have to encrypt data of length 20. However, the first 8 chars are always the same and known by everyone. Ex: Always starts with api-key=. Does including or removing the 8 first chars affect the security of the system?
Ex: encrypt('api-key=askjdhaskdhaskd') vs 'api-key=' + encrypt('askjdhaskdhaskd')
Does including or removing the 8 first chars affect the security of the system?
Yes, but only slightly.
CBC mode with a static IV is deterministic, which means that an attacker who only observes ciphertexts can determine if the same plaintext prefix was sent before. Since the first 8 bytes are known to be static, the chance for the next 8 bytes of the first block are much more probable to equal another API key, which does not necessarily match in its entirety. Whether this information is useful to the attacker is a completely different question.
It would be better to always generate an unpredictable (read: random) IV for CBC mode instead of relying on the same IV that is derived from a password. An IV is always 16 bytes or 32 hex-encoded characters long for AES regardless of key size.
Some example code:
var crypto = require('crypto');
var algo = 'aes-256-cbc';
var algoSecret = 'mySecret';
var key = crypto.pbkdf2Sync(algoSecret, 'salt', 1000, 256, 'sha256');
// the key can also be stored in Hex in order to prevent PBKDF2 invocation
var encrypt = function(secret){
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv(algo, key, iv);
var crypted = cipher.update(secret,'utf8','hex')
crypted += cipher.final('hex');
return iv.toString('hex') + crypted;
}
var decrypt = function(text){
var iv = new Buffer(text.slice(0, 32), 'hex');
text = text.slice(32);
var decipher = crypto.createDecipheriv(algo, key, iv);
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
return dec;
}
This is still not enough, because this code might be vulnerable to the padding oracle attack depending on your communication architecture. You should authenticate the ciphertexts with a message authentication code (MAC). A popular choice is HMAC-SHA256 for "encrypt-then-MAC".
var crypto = require('crypto');
var algo = 'aes-256-cbc';
var algoSecret = 'mySecret';
var key = crypto.pbkdf2Sync(algoSecret, 'salt', 1000, 512, 'sha512');
var keyMac = key.slice(32);
var keyEnc = key.slice(0, 32);
var encrypt = function(secret){
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv(algo, keyEnc, iv);
var crypted = cipher.update(secret,'utf8','hex')
crypted += cipher.final('hex');
var ct = iv.toString('hex') + crypted;
var hmac = crypto.createHmac('sha256', keyMac);
hmac.update(ct);
return ct + hmac.digest('hex');
}
var decrypt = function(text){
var hmac = crypto.createHmac('sha256', keyMac);
hmac.update(text.slice(0, -64));
if (hmac.digest('hex') !== text.slice(-64)) { // TODO: contant-time comparison
// TODO: do some decoy decryption
return false;
}
var iv = new Buffer(text.slice(0, 32), 'hex');
text = text.slice(32, -64);
var decipher = crypto.createDecipheriv(algo, keyEnc, iv);
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
return dec;
}

Secure token created in node different from .net

I'm trying to implement reCaptcha Secure Tokens in nodejs.
Looked at the examples made in Java and in .NET and created this version for node:
exports.getSecureToken = function() {
var algorithm = 'aes-128-ecb';
var tokenObj = { session_id: 'ab0069ec-3c2c-436c-868b-43c7a10db229'/*uuid.v4()*/, ts_ms: 1446560931992/*(new Date()).getTime()*/ };
var text = JSON.stringify(tokenObj);
var shaHash = new Buffer(crypto.createHash('sha1').update('6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO'/*config.reCAPTCHASecret*/).digest('hex'), 'hex');
var key = shaHash.slice(0, 16);
var cipher = crypto.createCipher(algorithm, key, key);
var encryptedToken = cipher.update(text, 'utf8', 'base64') + cipher.final('base64');
var result = encryptedToken.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
return result;
};
Problem is that in .NET I get a token that works (using the right key not included in the post), but in node I get a different token for the same input, and it doesn't works:
.NET - LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI
node - EGr7drd1JEylwzLGakZ6dpPRSf2nFdpzHOrJlLZlyHYmVRj5obAw7WjPt4W5l0vsywNEqCQ-2_d7qIZOMiOedianfBrQPOBaOmmq44IOB8Q
I got to see that key and input are the same (in .NET and node) right at the moment before encryption, so the problem must(?) be the cipher, any clues?
.NET code for reference:
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(EncryptJsonToken(GetJsonToken()));
}
public static string GetJsonToken()
{
//Example: {"session_id": e6e9c56e-a7da-43b8-89fa-8e668cc0b86f,"ts_ms":1421774317718}
string jsonRequest = "{" + string.Format("\"session_id\": {0},\"ts_ms\":{1}", "ab0069ec-3c2c-436c-868b-43c7a10db229", 1446560931992) + "}";
return jsonRequest;
}
public static byte[] getKey()
{
string secretKey = "6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO";
SHA1 sha = SHA1.Create();
byte[] dataToHash = Encoding.UTF8.GetBytes(secretKey);
byte[] shaHash = sha.ComputeHash(dataToHash);
byte[] first16OfHash = new byte[16];
Array.Copy(shaHash, first16OfHash, 16);
return first16OfHash;
}
public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.ECB;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
public static string EncryptJsonToken(string jsonToken)
{
byte[] encrypted = EncryptStringToBytes_Aes(jsonToken, getKey(), getKey());
//Base64 encode the encrypted data
//Also applys the URL variant of base64 encoding, unfortunately the HttpServerUtility.UrlTokenEncode(encrypted) seems to truncate the last value from the string so we can't use it?
return Convert.ToBase64String(encrypted, Base64FormattingOptions.None).Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
}
To debug in .NET: DEMO
You have two problems:
You're using JSON.stringify() to produce a valid JSON string, but the GetJsonToken() method in the C# code doesn't produce a valid JSON string. There are " missing for the UUID and there is a space between the session_id key and its value for some reason. You have to reflect those differences in JavaScript:
var uuidToken = "ab0069ec-3c2c-436c-868b-43c7a10db229";
var time = 1446560931992;
var text = "{\"session_id\": "+uuidToken+",\"ts_ms\":"+time+"}";
There is no such function crypto.createCipher(algorithm, key, key). There is however crypto.createCipheriv(algorithm, key, iv). createCipher(algorithm, password) can be used if one has a password instead of a key which you don't have. Since there is no IV for ECB mode, you can pass in an empty (binary) string as the IV.
Full code:
var crypto = require("crypto");
var algorithm = 'aes-128-ecb';
var uuidToken = "ab0069ec-3c2c-436c-868b-43c7a10db229";
var time = 1446560931992;
var text = "{\"session_id\": "+uuidToken+",\"ts_ms\":"+time+"}";
console.log("Token: " + text);
var shaHash = crypto.createHash('sha1').update('6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO').digest();
var key = shaHash.slice(0, 16);
var cipher = crypto.createCipheriv(algorithm, key, "");
var encryptedToken = cipher.update(text, 'utf8', 'base64') + cipher.final('base64');
var result = encryptedToken.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
console.log("result: " + result);
console.log("expected: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI");
Output:
Token: {"session_id": ab0069ec-3c2c-436c-868b-43c7a10db229,"ts_ms":1446560931992}
result: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI
expected: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI

Decrypting AES256 with node.js returns wrong final block length

Using this Gist I was able to successfully decrypt AES256 in Node.js 0.8.7. Then when I upgraded to Node.js 0.10.24, I now see this error:
TypeError: error:0606506D:digital envelope
routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.Cipher.final (crypto.js:292:27)
Here is the decrypt code from the Gist (shown here for convenience):
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
decoded = decipher.update(encryptdata);
decoded += decipher.final();
return decoded;
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv),
encryptdata = encipher.update(cleardata);
encryptdata += encipher.final();
encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = 'a2xhcgAAAAAAAAAA',
buf = "Here is some data for the encrypt", // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc);
console.warn("decrypt all: " + dec);
Ok, so there was a change to Crypto in the switch from 0.8 to 0.10 Crypto methods return Buffer objects by default, rather than binary-encoded strings
This means the above code needs to specify encodings.
These four lines:
decoded = decipher.update(encryptdata);
decoded += decipher.final();
encryptdata = encipher.update(cleardata);
encryptdata += encipher.final();
Are changed to:
decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');
This worked for me, but I am open to other suggestions.
As your answer states, those functions work with Buffers now unless you specify an encoding. That said, you'd be better off avoiding binary encoded strings entirely and treat everything as Buffers until you strictly need a string for something. This way you can also use your encryption helpers to process non-text content.
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
decipher.update(encryptdata),
decipher.final()
]);
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
encipher.update(cleardata),
encipher.final()
]);
}
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = new Buffer('a2xhcgAAAAAAAAAA'),
buf = new Buffer("Here is some data for the encrypt"), // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc.toString('base64'));
console.warn("decrypt all: " + dec.toString('utf8'));
My issue was that the string I was passing to my decrypt function was empty. I built in a check for empty strings and I did not receive the message again.
decrypt: function(text){
if(text.length == 0){
return text;
}
return this.decipher.update(text, 'hex', 'utf8') + this.decipher.final('utf8');
}

Bad decrypt on NodeJS Triple DES implementation?

var cardInfo = "<Card><CVV></CVV><CardNumber></CardNumber><ExpMonth></ExpMonth><ExpYear></ExpYear><Member></Member></Card>"
function genKeyPair(passphrase){
var iv = crypto.createHash('md5').update(passphrase).digest('hex').substring(0, 8)
var key = crypto.createHash('md5').update(passphrase).digest('hex').substring(0, 24)
return {
key: key,
iv: iv
}
}
function encrypt3DES(key, vector, data){
var encryptor = crypto.createCipheriv('des3', key, vector)
var raw = new Buffer(data)
encryptor.update(raw)
var encrypted = encryptor.final()
return encrypted
}
function decrypt3DES(key, vector, data){
var decryptor = crypto.createDecipheriv('des3', key, vector)
decryptor.update(data)
var decrypted = decryptor.final()
return decrypted
}
var key = genKeyPair('test')
var data3DES = encrypt3DES(key.key, key.iv, cardInfo)
var decryptedCard = decrypt3DES(key.key, key.iv, data3DES)
So, I get a "bad decrypt" on decryptor.final() and can't figure out why.
Node expects a buffer when encrypting so you see I provide that in the beginning of the encrypt3DES
I put the raw buffer output from encryption straight into the decrypt method
What am I doing wrong here?
DISCLAIMER
No, this is not going to be used in production. I'm just toying around so please hold with the "you don't know what you're doing so you shouldn't do it" talk
The results of update are thrown away in your code:
Returns the enciphered contents, and can be called many times with new data as it is streamed.
The code also uses 3DES ABC keys that do not contain enough entropy (keys should be binary data, not hexadecimals). At least try to use crypto.createCipher(algorithm, password) or try and find an implementation of PBKDF2 in JavaScript.
here is algorithm related key and iv lengths relations, as
DES-ECB Key: 8; IV: 0
DES-CBC Key: 8; IV: 8
DES-CFB Key: 8; IV: 8
DES-CFB1 Key: 8; IV: 8
DES-CFB8 Key: 8; IV: 8
DES-EDE-CBC Key: 16; IV: 8
DES-EDE-CFB Key: 16; IV: 8
DES-EDE-OFB Key: 16; IV: 8
DES-EDE3-CBC Key: 24; IV: 8
DESX-CBC Key: 24; IV: 8
and, this is a runnable example
const crypto = require('crypto');
const iv = '12345678';
const key = '123456'.padEnd(24,'0');
const ivHex = Buffer.from(iv, 'utf8');
const keyHex = Buffer.from(key, 'utf8');
const decrypt = (text)=>{
const cipher = crypto.createDecipheriv('DES-EDE3-CBC', keyHex,ivHex);
let c = cipher.update(text, 'base64','utf8')
c += cipher.final('utf8');
return c;
}
const encrypt = (text)=>{
const cipher = crypto.createCipheriv('DES-EDE3-CBC', keyHex,ivHex);
let c = cipher.update(text, 'utf8' ,'base64');
c+=cipher.final('base64');
return c;
}
const text = '7LBIMxZKDB0=';
const plaintext = decrypt(text);
console.log(plaintext);//123456
const cipherText = encrypt(plaintext);
console.log(cipherText, text === cipherText);//7LBIMxZKDB0= true
hope it helps.

Resources