RSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and it is different from the decryption key which is kept secret (private). In RSA, this asymmetry is based on the practical difficulty of the factorization of the product of two large prime numbers, the "factoring problem". The acronym RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly described the algorithm in 1978. Clifford Cocks, an English mathematician working for the British intelligence agency Government Communications Headquarters (GCHQ), had developed an equivalent system in 1973, but this was not declassified until 1997.

Public key cryptography uses a pair of keys for encryption. Distribute the public key to whoever needs it but safely secure the private key.

Public key cryptography can be used in two modes:

• Encryption: Only the private key can decrypt the data encrypted with the public key.
• Authentication: Data encrypted with the private key can only be decrypted with the public key thus proving who the data came from.

# 1 KeyPair

A key Pair is a pair of a public and a private key. Next you can see how to generate a Key Pair and to extract public and private keys in PEM format:

Copy
<script>
var kp = new Ax.crypt.KeyPair("RSA", 2048);

var rsa = new Ax.crypt.RSA(kp);

console.log("PrivateKey :" + kp.getPrivateKey());
console.log("PrivateKey :" + kp.getPrivateKeyAsPEM());
console.log(" PublicKey :" + kp.getPublicKey());
console.log(" PublicKey :" + kp.getPublicKeyAsPEM());

var pub_pem  = rsa.toPublicKey();
var pri_pem  = rsa.toPrivateKey();
console.log(pub_pem);
console.log(pri_pem);
</script>

# 2 Encrypt

To encrypt a message using a geerated public key.

Copy
<script>
var kp = new Ax.crypt.KeyPair("RSA", 2048);
var rsa = new Ax.crypt.RSA(kp);

var secret = "This is a secret message";
// encrypt a string or byte[]
// string is converted to byte[] using utf-8 encoding
var msg_encrypted = rsa.encrypt(secret);
console.log(msg_encrypted);
console.log("----");
console.log(rsa.toBase64(msg_encrypted));
</script>

# 3 Decrypt

To decrypt a crypted message.

Copy
<script>
var kp = new Ax.crypt.KeyPair("RSA", 2048);
var rsa = new Ax.crypt.RSA(kp);

var secret = "This is a secret message";
// msg_encrypted is the encrypted message stored in base64
var msg_encrypted = rsa.encrypt(secret);

// msg_decrypted is a byte[] of message.
var msg_decrypted = rsa.decrypt(msg_encrypted);

// Convert to string before print using rsa toString method.
console.log(new Ax.lang.String(msg_decrypted, "utf-8"));

</script>