NodeJS Forge - Convert Encrypted byte string to hex character array

Viewed 762

I am using NodeJS-Forge to encrypt a string using a Public Key.

var text = 'testingtext';
var pemPublicKey = "*******";
var publicKeyFromPem = forge.pki.publicKeyFromPem(pemPublicKey);

const options = {
    md: forge.md.sha256.create(),
    mgf1: {
        md: forge.md.sha1.create()
    }
}

var encrypted = publicKeyFromPem.encrypt(text, 'RSAES-OAEP', options);
console.log(encrypted);

I am getting encrypted string as below byte string.

 ZIŸ0ÊQÁ@ìœÆ:Øê%       ÞÂÚÇìm,ÿ™hµÅÇ4­Ó¶/ çÎï_žå´Ï_rÓÆça:r¤—T{Zç{á£#ã?ݺh=ÝïW˜„HK²ù^Ǻè[áÔQQ€Ì„A¦¢R‡à*~`
éz©‹×„ÔDB™íFgèÞ$¯S®oE J

Then i need to get hex string and then to string format. I am using below code to get this hashed string.

var buffer = forge.util.createBuffer(encrypted, 'raw');
var hashstring = buffer.toHex().toString().replace(/,/g, '');
console.log(hashstring);

But not getting correct result. Following is the steps from the client.

  1. Convert encrypted byte data to Character array using Hex encoding.
  2. Convert the character array to String.

I am not sure what is the issue here.

1 Answers

As the client asks for a hexstring I would use this function to convert the byte array ('encrypted') to a string:

function toHexString(byteArray) {
  return Array.from(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('')
}
Related