Reputation: 1
// import the path module
const path = require('node:path');
const crypto = require('crypto');
// get the public key certificate
const CRTpath = path.basename('./PublicKey.crt');
const GenKey = crypto.randomBytes(32);
// encode key to Base 64
const base64Key = Buffer.from(GenKey).toString('base64');
const OBJ = {
username: "xxx",
password: "xasadsd",
encryptKey: base64Key,
refreshToken: "false"
}
let jsonOBJ = JSON.stringify(OBJ);
function encryptString (plaintext, publicKeyFile) {
const publicKey = fs.readFileSync(publicKeyFile, "utf8");
// publicEncrypt() method with its parameters
const encrypted = crypto.publicEncrypt(
publicKey, Buffer.from(plaintext));
return encrypted;
}
const encrypted = encryptString(jsonOBJ, CRTpath);
const baseEncrypted = Buffer.from(encrypted, 'utf8').toString("base64");
EDIT 1: I need to send a paylod as follows:
{
requestID: "string", // this part is OK
payload: "" // value of encrypted above
}
EDIT 2(specifications):
5.1.10. Steps to produce Authentication JSON in format requested Steps
So far this is not working and returns a 404.
a) I am trying to use Nodejs Crypto module to generate a random key using AES 256(AES/ECB/PKCS5Padding) algorithm.
b) I have to encrypt the key using a public key (.crt) files // This part i can deal with
c) Then send it as payload... // this part i can deal with
But however after numerous tries and reading docs, i could not wrap my head around the point a)... I believe that i have wrongly done the ecryption before encoding to base64
Any help or leads will be most welcomed... many thanks
Upvotes: 0
Views: 608
Reputation: 299495
I am trying to use Nodejs Crypto module to generate a random key using AES 256(AES/ECB/PKCS5Padding) algorithm.
This is not what you're doing, and not something you would generally ever do. (It's technically possible to directly use AES to generate a key, but for any reason you'd want to, there are better solutions.)
What you are doing (correctly, I believe) is generating a random AES key. An AES key is just a string of random bytes of a specific length. It isn't related to a mode (like ECB) or padding (like PKCS5). AES doesn't generate the key. It uses the key. Good AES keys are always random, or "effectively random" (which is a technical term with a precise definition) such as the output of PBKDF2. They have no internal structure at all. No headers. No flags. Nothing. Just a specified number of random bytes.
What you seem to have done here is make a random AES key, encrypted it using the server's public key, and sent it to the server. Public-private key encryption is slow. So you only use it to encrypt the AES key. AES is very fast. Now that you and the server share a key, you can quickly share encrypted data. What you've shown here is an extremely common approach.
Upvotes: 0