Back

Technologies:

javascriptjavascript
avatar
Tolerim
21 days ago

Can a public key be created using the x.509 specification in a Postman pre-request script?

I need to generate a public key from a base64 encoded string in Postman pre request script using JavaScript. I have already achieved this with Kotlin on the code level. However, I now require a JavaScript solution for Postman. Here is the Kotlin code for reference:

fun loadPublicKey(key64: String): PublicKey? {
    val data: ByteArray = BaseEncoding.base64().decode(key64)
    val spec = X509EncodedKeySpec(data)
    val fact = KeyFactory.getInstance("RSA")
    return fact.generatePublic(spec)
}
Thank you for your help.

Answers(1)
avatar
Tolerim
21 days ago
Verified Answer
To generate a public key from a base64 string in Postman pre-request script using JavaScript, you can use the following code:
// import required classes
const CryptoJS = require('crypto-js');
const forge = require('node-forge');

// decode base64 string to Uint8Array buffer
const key64 = 'your_base64_encoded_public_key';
const buffer = new Uint8Array(
  atob(key64)
    .split('')
    .map((char) => char.charCodeAt(0))
);

// generate public key
const pem = forge.pki.publicKeyToPem(
  forge.pki.setRsaPublicKey(
    new Uint8Array(
      CryptoJS.lib.WordArray.create(buffer)
        .words
    )
  )
);

console.log(pem); // to verify the generated public key
Please note that you need to install the crypto-js and node-forge libraries for this code to work. You can install them using npm by running the following command:
npm install crypto-js node-forge --save
;