Decrypting in Javascript

Joined
Jun 3, 2023
Messages
5
Reaction score
0
I have a scenario I have a cipher text and RSA private key (encrypted form) along with AES 256 Key. My concern is I want JavaScript code that will first decrypt RSA private key using AES 256 key I don’t have initialization vector(which is randomly generated 16 bit). The decrypted RSA private key is then used to decrypt the main cipher text.
We can decrypt the data with below ruby code but we want to achieve same in Javascript

The ruby code:

require 'openssl'
require 'base64'
private_key_path = 'C:\Users\User\Documents\Ruby\private3.pem'
passphrase = 'xxxxxxxxxxxxxxxxxx'
begin
private_key = OpenSSL::pKey::RSA.new(File.read(private_key_path), passphrase)
encrypted_ssn = File.read('C:\Users\User\Documents\RubyC=\input_case.txt')
decrypted_ssn = private_key.private_decrypt(Base64.decode64(encrypted_ssn))
puts "Decrypted SSN: #{decrypted_ssn}"
rescue Errno::ENOENT => e
puts "Error: #{e.message}. Make sure the file paths are correct."
rescue OpenSSL::pKey::RSAError => e
puts "Error: #{e.message}. Check if the private key or passphrase is correct."
end


Key Formats

(Input Case)
Cipher Text Format: rnIlnXweYGYX107Lz7nAIYSASUpZsZoAAUS9zueA=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Private key:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,A7AF3A76C321D9FFFFFFFFFFFFFF

SOj8/nY3qkQKKcpjIXxCSIJey8LVuvYLMeZL+8BRrdnxM1RTNAMLeO3Gd7hD7PLJ
oBRsLmynXYVwIM6l0G1B+KBjXjb1K9iwnyrGFSbA3Fx8LnNaMHnfW+A3+bUUiBt0XXXXXXXXXXXXX…

-----END RSA PRIVATE KEY-----
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
To achieve the same decryption process in JavaScript, you can use the crypto module available in Node.js. Here's an example of how you can decrypt the RSA private key using AES-256 key and then use the decrypted RSA private key to decrypt the main ciphertext:

javascriptCopy code
const crypto = require('crypto');
const fs = require('fs');

const privateKeyPath = 'path/to/private3.pem';
const passphrase = 'xxxxxxxxxxxxxxxxxx';
const encryptedSSNPath = 'path/to/input_case.txt';
const aes256Key = 'AES-256 key'; // Replace with your AES-256 key

try {
// Read the RSA private key
const privateKey = fs.readFileSync(privateKeyPath);

// Decrypt the RSA private key using AES-256 key
const decipher = crypto.createDecipher('aes256', aes256Key);
decipher.update(privateKey);
const decryptedPrivateKey = decipher.final('utf8');

// Load the decrypted RSA private key
const rsaPrivateKey = crypto.createPrivateKey({
key: decryptedPrivateKey,
format: 'pem',
passphrase: passphrase
});

// Read the encrypted ciphertext
const encryptedSSN = fs.readFileSync(encryptedSSNPath, 'base64');

// Decrypt the main ciphertext using the RSA private key
const decryptedSSN = crypto.privateDecrypt(
{
key: rsaPrivateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
},
Buffer.from(encryptedSSN, 'base64')
);

console.log('Decrypted SSN:', decryptedSSN.toString());
} catch (error) {
console.error('Error:', error.message);
}

Make sure you replace 'path/to/private3.pem' with the actual path to your private key file, 'xxxxxxxxxxxxxxxxxx' with your actual passphrase, 'path/to/input_case.txt' with the path to your encrypted ciphertext file, and 'AES-256 key' with your actual AES-256 key.

Note that this code is meant to be run in a Node.js environment and utilizes the built-in crypto module. It may not work in a browser-based JavaScript environment due to differences in available modules and file system access.
 
Joined
Jun 3, 2023
Messages
5
Reaction score
0
Hi Phor0244,
First all thank you solution

I have just one concern the function you used crypto.createDecipher('aes256', aes256Key); is deprecated by the node and introduced the new function


const crypto = require('crypto');

const algorithm = 'aes-256-cbc'; // The encryption algorithm to use
const key = 'YOUR_ENCRYPTION_KEY'; // The secret key used for encryption
const iv = 'YOUR_INITIALIZATION_VECTOR'; // The initialization vector

const decipher = crypto.createDecipheriv(algorithm, key, iv);


Here we are facing the main issue the const iv (Initialization vector) is getting generated randomly 16 bit or 32 bit. We are not getting the exact iv. This leads to getting error as initialization vector invalid

1685875167944.png

Could please help in the code in adhrence to this iv vector logic??
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
Certainly! I apologize for the outdated code. Here's an updated version that generates a random initialization vector (IV) of the correct length for AES-256-CBC encryption:
JavaScript:
const crypto = require('crypto');

const algorithm = 'aes-256-cbc'; // The encryption algorithm to use
const key = 'YOUR_ENCRYPTION_KEY'; // The secret key used for encryption
const ivLength = 16; // The desired IV length in bytes

// Generate a random IV
const iv = crypto.randomBytes(ivLength);

const decipher = crypto.createDecipheriv(algorithm, key, iv);
In the code above, crypto.randomBytes(ivLength) is used to generate a random IV of the specified length (ivLength). AES-256-CBC requires a 16-byte (128-bit) IV.

Make sure to replace 'YOUR_ENCRYPTION_KEY' with your actual encryption key.
 
Joined
Jun 3, 2023
Messages
5
Reaction score
0
Hi Phro0244,


Again thank you for the solution but still it is giving same error. Invalid Initialization Vector the code is as follows


const crypto = require('crypto');
const fs = require('fs');
const privateKeyPath = '....../private3.pem';
const passphrase = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const encryptedSSNPath = '......./input_case.txt';
const aes256Key = 'A7AF3A76C321D9DDDDDDFFFFFF'; // Replace with your AES-256 key
try {
// Read the RSA private key
const privateKey = fs.readFileSync(privateKeyPath);
// Decrypt the RSA private key using AES-256 key
const decipher = crypto.createDecipheriv('aes-256-cbc', aes256Key, '360abf07e88ecff63b88577569404272105f668747f364f2e110dde43f38f25f');
let decryptedPrivateKey = decipher.update(privateKey, 'base64', 'utf8');
decryptedPrivateKey += decipher.final('utf8');
// Load the decrypted RSA private key
const rsaPrivateKey = crypto.createPrivateKey({
key: decryptedPrivateKey,
format: 'pem',
passphrase: passphrase
});
// Read the encrypted ciphertext
const encryptedSSN = fs.readFileSync(encryptedSSNPath, 'base64');
// Decrypt the main ciphertext using the RSA private key
const decryptedSSN = crypto.privateDecrypt(
{
key: rsaPrivateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
},
Buffer.from(encryptedSSN, 'base64')
);
console.log('Decrypted SSN:', decryptedSSN.toString());
} catch (error) {
console.error('Error:', error.message);
}



1685958764292.png
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
"Invalid initialization vector" error indicates that the initialization vector (IV) used for AES-256 decryption is incorrect.

In your code, you are using the value '360abf07e88ecff63b88577569404272105f668747f364f2e110dde43f38f25f' as the initialization vector. It's important to note that the initialization vector should be a random and unique value for each encryption operation.

To fix this error, you need to generate a random initialization vector and use it for AES-256 decryption. You can use the crypto.randomBytes method to generate a random initialization vector. Here's an example code to guide you:

// Generate a random initialization vector
const iv = crypto.randomBytes(16);

// Use the initialization vector for AES-256 decryption
const decipher = crypto.createDecipheriv('aes-256-cbc', aes256Key, iv);

Make sure to update the code with the appropriate random initialization vector generation and use it in the createDecipheriv method.

Also, remember to modify the AES-256 key (aes256Key) and ensure that all file paths are correct.
 
Joined
Jun 3, 2023
Messages
5
Reaction score
0
1686129015960.png

1686129060193.png

Hi Phro0244,


Thank you for your above solution now we got something new error termed as "Provider routines:: wrong final block length". We made the changes as per your previous response. Still it is giving following error when we use 16 bit IV we are getting the error as "Provider routines:: wrong final block length" and when we try with 32 bit IV we are getting same previous error "Invalid Initialization". I am attaching code benefit do check and let us know what more we can do to achieve the expected result.

// Generate a 16-bit (128-bit) IV
const iv16 = crypto.randomBytes(16);
console.log('16-bit IV:', iv16.toString('hex'));
// Generate a 32-bit (256-bit) IV
const iv32 = crypto.randomBytes(32);
console.log('32-bit IV:', iv32.toString('hex'));


const crypto = require('crypto');
const fs = require('fs');
const privateKeyPath = '....../private3.pem';
const passphrase = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const encryptedSSNPath = '......./input_case.txt';
const aes256Key = 'A7AF3A76C321D9DDDDDDFFFFFF'; // Replace with your AES-256 key
try {
// Read the RSA private key
const privateKey = fs.readFileSync(privateKeyPath);
// Decrypt the RSA private key using AES-256 key
const decipher = crypto.createDecipheriv('aes-256-cbc', aes256Key, '360abf07e88ecff63b88577569404272105f668747f364f2e110dde43f38f25f');
let decryptedPrivateKey = decipher.update(privateKey, 'base64', 'utf8');
decryptedPrivateKey += decipher.final('utf8');
// Load the decrypted RSA private key
const rsaPrivateKey = crypto.createPrivateKey({
key: decryptedPrivateKey,
format: 'pem',
passphrase: passphrase
});
// Read the encrypted ciphertext
const encryptedSSN = fs.readFileSync(encryptedSSNPath, 'base64');
// Decrypt the main ciphertext using the RSA private key
const decryptedSSN = crypto.privateDecrypt(
{
key: rsaPrivateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
},
Buffer.from(encryptedSSN, 'base64')
);
console.log('Decrypted SSN:', decryptedSSN.toString());
} catch (error) {
console.error('Error:', error.message);
}
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
The error "Provider routines::wrong final block length" typically occurs when there is a mismatch between the key size and the initialization vector (IV) size in AES encryption. In your code, you are generating a 16-byte IV and a 32-byte IV, but the key you are using is a 256-bit (32-byte) key.

To fix this issue, you need to ensure that the IV size matches the block size of the encryption algorithm. In AES-CBC mode, the block size is 128 bits (16 bytes). Therefore, you should use a 16-byte IV for AES-256-CBC encryption.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top