Created
November 9, 2021 21:59
-
-
Save mayankchoubey/66b5594556149656a8b0232b7ec93799 to your computer and use it in GitHub Desktop.
AES encryption & decryption in Deno
This file contains hidden or 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
| import { | |
| decode as hd, | |
| encode as he, | |
| } from "https://deno.land/std/encoding/hex.ts"; | |
| const te = (s: string) => new TextEncoder().encode(s), | |
| td = (d: Uint8Array) => new TextDecoder().decode(d); | |
| const rawKey = new Uint8Array([ | |
| 238, | |
| 17, | |
| 126, | |
| 165, | |
| 51, | |
| 88, | |
| 22, | |
| 218, | |
| 53, | |
| 172, | |
| 137, | |
| 113, | |
| 210, | |
| 198, | |
| 109, | |
| 117, | |
| ]); | |
| const key = await crypto.subtle.importKey( | |
| "raw", | |
| rawKey.buffer, | |
| "AES-CBC", | |
| true, | |
| ["encrypt", "decrypt"], | |
| ); | |
| const plainText = "Learning Deno is fun!!"; | |
| const iv = await crypto.getRandomValues(new Uint8Array(16)); | |
| const encrypted = await crypto.subtle.encrypt( | |
| { name: "AES-CBC", iv }, | |
| key, | |
| te(plainText), | |
| ); | |
| const encryptedBytes = new Uint8Array(encrypted); | |
| const hexBytes = td(he(encryptedBytes)); | |
| console.log("Encrypted hex data", hexBytes); | |
| const decrypted = await crypto.subtle.decrypt( | |
| { name: "AES-CBC", iv }, | |
| key, | |
| hd(te(hexBytes)), | |
| ); | |
| const decryptedBytes = new Uint8Array(decrypted); | |
| const decryptedText = td(decryptedBytes); | |
| console.log("Decrypted data", decryptedText); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment