Now with first version of encryption!
This commit is contained in:
30
src/lib/ae_utils/ae_utils__crypto.ts
Normal file
30
src/lib/ae_utils/ae_utils__crypto.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
async function generate_iv() {
|
||||
const data = new Uint8Array(16);
|
||||
crypto.getRandomValues(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
export let encrypt_content = async function encrypt_content(
|
||||
content: string, keyData: string
|
||||
) {
|
||||
const iv = await generate_iv();
|
||||
const keyBytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(keyData));
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, { name: 'AES-CBC' }, false, ['encrypt']);
|
||||
const encodedContent = await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, key, new TextEncoder().encode(content));
|
||||
const base64 = btoa(String.fromCharCode(...new Uint8Array(encodedContent)));
|
||||
console.log('Base64 Encoded Content:', base64);
|
||||
return { base64, iv };
|
||||
}
|
||||
|
||||
export let decrypt_content = async function decrypt_content(
|
||||
base64Content: string, iv: Uint8Array, keyData: string
|
||||
) {
|
||||
const keyBytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(keyData));
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, { name: 'AES-CBC' }, false, ['decrypt']);
|
||||
const encryptedContent = Uint8Array.from(atob(base64Content), c => c.charCodeAt(0));
|
||||
const decryptedContent = await crypto.subtle.decrypt({ name: 'AES-CBC', iv }, key, encryptedContent);
|
||||
const decodedContent = new TextDecoder().decode(decryptedContent);
|
||||
// console.log('Decrypted Content:', decodedContent);
|
||||
return decodedContent;
|
||||
}
|
||||
Reference in New Issue
Block a user