(text: string)
| 61 | } |
| 62 | |
| 63 | export async function encrypt(text: string): Promise<string> { |
| 64 | if (!text) { |
| 65 | throw new Error("Cannot encrypt empty or null text"); |
| 66 | } |
| 67 | |
| 68 | try { |
| 69 | const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH)); |
| 70 | const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH)); |
| 71 | const key = await deriveKey(salt); |
| 72 | |
| 73 | const encoded = new TextEncoder().encode(text); |
| 74 | const encrypted = await crypto.subtle.encrypt( |
| 75 | { |
| 76 | name: ALGORITHM.name, |
| 77 | iv, |
| 78 | }, |
| 79 | key, |
| 80 | encoded, |
| 81 | ); |
| 82 | |
| 83 | const result = Buffer.concat([ |
| 84 | Buffer.from(salt), |
| 85 | Buffer.from(iv), |
| 86 | Buffer.from(encrypted), |
| 87 | ]); |
| 88 | |
| 89 | return result.toString("base64"); |
| 90 | } catch (error: unknown) { |
| 91 | if (error instanceof Error) { |
| 92 | throw new Error(`Encryption failed: ${error.message}`); |
| 93 | } |
| 94 | throw new Error("Encryption failed"); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | export async function decrypt(encryptedText: string): Promise<string> { |
| 99 | if (!encryptedText) { |
no test coverage detected