Created
September 28, 2019 14:53
-
-
Save agnelvishal/13077afe05d5c61a0c054fce5f6a9208 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt using Js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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