1 | import { stringToU8a, u8aFixLength } from '@polkadot/util';
|
2 | import { naclDecrypt } from '../nacl/index.js';
|
3 | import { scryptEncode, scryptFromU8a } from '../scrypt/index.js';
|
4 | import { ENCODING, NONCE_LENGTH, SCRYPT_LENGTH } from './constants.js';
|
5 | export function jsonDecryptData(encrypted, passphrase, encType = ENCODING) {
|
6 | if (!encrypted) {
|
7 | throw new Error('No encrypted data available to decode');
|
8 | }
|
9 | else if (encType.includes('xsalsa20-poly1305') && !passphrase) {
|
10 | throw new Error('Password required to decode encrypted data');
|
11 | }
|
12 | let encoded = encrypted;
|
13 | if (passphrase) {
|
14 | let password;
|
15 | if (encType.includes('scrypt')) {
|
16 | const { params, salt } = scryptFromU8a(encrypted);
|
17 | password = scryptEncode(passphrase, salt, params).password;
|
18 | encrypted = encrypted.subarray(SCRYPT_LENGTH);
|
19 | }
|
20 | else {
|
21 | password = stringToU8a(passphrase);
|
22 | }
|
23 | encoded = naclDecrypt(encrypted.subarray(NONCE_LENGTH), encrypted.subarray(0, NONCE_LENGTH), u8aFixLength(password, 256, true));
|
24 | }
|
25 | if (!encoded) {
|
26 | throw new Error('Unable to decode using the supplied passphrase');
|
27 | }
|
28 | return encoded;
|
29 | }
|