(plaintext: string)
| 38 | } |
| 39 | |
| 40 | async encrypt(plaintext: string): Promise<SecretEncryptionMaterial> { |
| 41 | const masterKey = await this.keyPromise; |
| 42 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 43 | const encoder = new TextEncoder(); |
| 44 | const encoded = encoder.encode(plaintext); |
| 45 | |
| 46 | const ciphertext = await crypto.subtle.encrypt( |
| 47 | { name: 'AES-GCM', iv: SecretEncryption.toArrayBuffer(iv) }, |
| 48 | masterKey, |
| 49 | SecretEncryption.toArrayBuffer(encoded) |
| 50 | ); |
| 51 | |
| 52 | const ciphertextBytes = new Uint8Array(ciphertext); |
| 53 | if (ciphertextBytes.length < 16) { |
| 54 | throw new Error('Encrypted payload shorter than authentication tag length.'); |
| 55 | } |
| 56 | |
| 57 | const dataBytes = ciphertextBytes.slice(0, ciphertextBytes.length - 16); |
| 58 | const tagBytes = ciphertextBytes.slice(ciphertextBytes.length - 16); |
| 59 | |
| 60 | return { |
| 61 | ciphertext: SecretEncryption.encode(dataBytes), |
| 62 | authTag: SecretEncryption.encode(tagBytes), |
| 63 | iv: SecretEncryption.encode(iv), |
| 64 | keyId: this.keyId, |
| 65 | }; |
| 66 | } |
| 67 | |
| 68 | async decrypt(material: SecretEncryptionMaterial): Promise<string> { |
| 69 | const masterKey = await this.keyPromise; |
no test coverage detected