What is RSA Asymmetric Cryptography?
RSA (Rivest–Shamir–Adleman) is a public-key cryptosystem widely used for secure data transmission. In an asymmetric cryptographic system, two different mathematically linked keys are generated: a Public Key and a Private Key.
The Public Key can be shared with anyone. It is used to encrypt messages. However, once a message is encrypted with the Public Key, it can only be decrypted by the matching Private Key. The Private Key must be kept absolutely secret. RSA is the foundational technology behind HTTPS/TLS certificates, SSH logins, and JSON Web Token (JWT) RS256 signing.
How to generate an RSA Key Pair in JavaScript
You no longer need to execute OpenSSL commands in your terminal or install massive NPM packages to generate RSA keys. You can use the native browser Web Crypto API:
async function generateRSA() {
// 1. Generate the raw Key Pair
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048, // Can be 1024, 2048, or 4096
publicExponent: new Uint8Array([1, 0, 1]), // 65537 standard
hash: "SHA-256"
},
true, // extractable
["sign", "verify"]
);
// 2. Export them into binary ArrayBuffers
const publicKeyBuffer = await window.crypto.subtle.exportKey("spki", keyPair.publicKey);
const privateKeyBuffer = await window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
// You would then Base64 encode these buffers to create PEM strings
return { publicKeyBuffer, privateKeyBuffer };
}