Skip to content

Instantly share code, notes, and snippets.

@lynsei
Created January 24, 2025 17:22
Show Gist options
  • Save lynsei/403b6b878eae68d35452cf9de7976790 to your computer and use it in GitHub Desktop.
Save lynsei/403b6b878eae68d35452cf9de7976790 to your computer and use it in GitHub Desktop.
[deno] AES crypto CBC
import { writeFileStr, readFileStr } from "https://deno.land/std/fs/mod.ts";
import { crypto } from "https://deno.land/std/crypto/mod.ts";
async function encryptAndSave(results: any[], keyFile: string, dataFile: string) {
// Generate a random 256-bit (32 bytes) key and IV
const key = crypto.getRandomValues(new Uint8Array(32)); // AES-256
const iv = crypto.getRandomValues(new Uint8Array(16)); // AES block size
// Convert results to JSON string
const resultsJSON = JSON.stringify(results);
const encoder = new TextEncoder();
const encodedResults = encoder.encode(resultsJSON);
// Encrypt the JSON data
const cipherText = new Uint8Array(
await crypto.subtle.encrypt(
{ name: "AES-CBC", iv },
await crypto.subtle.importKey("raw", key, "AES-CBC", false, ["encrypt"]),
encodedResults
)
);
// Save the key and IV as a base64 encoded JSON
const keyData = {
key: btoa(String.fromCharCode(...key)),
iv: btoa(String.fromCharCode(...iv)),
};
await writeFileStr(keyFile, JSON.stringify(keyData));
// Save the encrypted data as base64
await writeFileStr(dataFile, btoa(String.fromCharCode(...cipherText)));
console.log("Data encrypted and saved successfully.");
}
// Usage
const results = [{ id: 1, value: "example" }, { id: 2, value: "test" }];
await encryptAndSave(results, "key.json", "data.enc");
async function decryptAndRetrieve(keyFile: string, dataFile: string): Promise<any[]> {
// Read the key and IV from the file
const keyData = JSON.parse(await readFileStr(keyFile));
const key = Uint8Array.from(atob(keyData.key), (c) => c.charCodeAt(0));
const iv = Uint8Array.from(atob(keyData.iv), (c) => c.charCodeAt(0));
// Read the encrypted data
const encryptedData = Uint8Array.from(
atob(await readFileStr(dataFile)),
(c) => c.charCodeAt(0)
);
// Decrypt the data
const decrypted = new Uint8Array(
await crypto.subtle.decrypt(
{ name: "AES-CBC", iv },
await crypto.subtle.importKey("raw", key, "AES-CBC", false, ["decrypt"]),
encryptedData
)
);
// Decode the decrypted data back to JSON
const decoder = new TextDecoder();
const resultsJSON = decoder.decode(decrypted);
return JSON.parse(resultsJSON);
}
// Usage
const decryptedResults = await decryptAndRetrieve("key.json", "data.enc");
console.log("Decrypted Results:", decryptedResults);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment