|
1 | 1 | import assert from 'assert'; |
2 | 2 | import { randomBytes } from 'crypto'; |
3 | 3 |
|
4 | | -import { decrypt, decryptV2, encrypt, encryptV2, V2Envelope } from '../../src'; |
| 4 | +import { decrypt, decryptAsync, decryptV2, encrypt, encryptV2, V2Envelope } from '../../src'; |
5 | 5 |
|
6 | 6 | describe('encryption methods tests', () => { |
7 | 7 | describe('encrypt', () => { |
@@ -138,4 +138,43 @@ describe('encryption methods tests', () => { |
138 | 138 | await assert.rejects(() => decryptV2(password, v1ct), /unsupported envelope version/); |
139 | 139 | }); |
140 | 140 | }); |
| 141 | + |
| 142 | + describe('decryptAsync (auto-detect v1/v2)', () => { |
| 143 | + const password = 'myPassword'; |
| 144 | + const plaintext = 'Hello, World!'; |
| 145 | + |
| 146 | + it('decrypts v1 data', async () => { |
| 147 | + const v1ct = encrypt(password, plaintext); |
| 148 | + const result = await decryptAsync(password, v1ct); |
| 149 | + assert.strictEqual(result, plaintext); |
| 150 | + }); |
| 151 | + |
| 152 | + it('decrypts v2 data', async () => { |
| 153 | + const v2ct = await encryptV2(password, plaintext); |
| 154 | + const result = await decryptAsync(password, v2ct); |
| 155 | + assert.strictEqual(result, plaintext); |
| 156 | + }); |
| 157 | + |
| 158 | + it('throws on wrong password for v1', async () => { |
| 159 | + const v1ct = encrypt(password, plaintext); |
| 160 | + await assert.rejects(() => decryptAsync('wrong', v1ct)); |
| 161 | + }); |
| 162 | + |
| 163 | + it('throws on wrong password for v2', async () => { |
| 164 | + const v2ct = await encryptV2(password, plaintext); |
| 165 | + await assert.rejects(() => decryptAsync('wrong', v2ct)); |
| 166 | + }); |
| 167 | + |
| 168 | + it('wrong password on v2 data does not fall through to v1 decrypt', async () => { |
| 169 | + const v2ct = await encryptV2(password, plaintext, { memorySize: 1024, iterations: 1, parallelism: 1 }); |
| 170 | + let caughtError: Error | undefined; |
| 171 | + try { |
| 172 | + await decryptAsync('wrong', v2ct); |
| 173 | + } catch (e) { |
| 174 | + caughtError = e as Error; |
| 175 | + } |
| 176 | + assert.ok(caughtError, 'should have thrown'); |
| 177 | + assert.ok(!caughtError.message?.includes('sjcl'), 'error must not be from SJCL'); |
| 178 | + }); |
| 179 | + }); |
141 | 180 | }); |
0 commit comments