Skip to content

Instantly share code, notes, and snippets.

@agnelvishal
Created September 28, 2019 14:53
Show Gist options
  • Save agnelvishal/13077afe05d5c61a0c054fce5f6a9208 to your computer and use it in GitHub Desktop.
Save agnelvishal/13077afe05d5c61a0c054fce5f6a9208 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt using Js
async function main() {
keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
function getMessageEncoding() {
let message = "hello"
let enc = new TextEncoder();
return enc.encode(message);
}
async function encryptMessage(publicKey) {
let encoded = getMessageEncoding();
let encrypted = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
publicKey,
encoded
);
return encrypted;
}
let encryptedOuput = await encryptMessage(keyPair.publicKey);
console.log(encryptedOuput);
async function decryptMessage(key) {
let decrypted = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
key,
encryptedOuput
);
let dec = new TextDecoder();
decrypted = dec.decode(decrypted);
return decrypted;
}
let decryptedOutput = await decryptMessage(keyPair.privateKey);
console.log(decryptedOutput);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment