|
| 1 | +import { argon2id } from '@bitgo/argon2'; |
| 2 | +import * as sjcl from '@bitgo/sjcl'; |
| 3 | +import { randomBytes, webcrypto } from 'crypto'; |
| 4 | +import * as t from 'io-ts'; |
| 5 | + |
| 6 | +import { base64String, boundedInt, decodeWithCodec } from './codecs'; |
| 7 | + |
| 8 | +const subtle = globalThis.crypto?.subtle ?? webcrypto.subtle; |
| 9 | + |
| 10 | +const ARGON2_DEFAULTS = { memorySize: 65536, iterations: 3, parallelism: 4, hashLength: 32, saltLength: 16 } as const; |
| 11 | +const ARGON2_MAX = { memorySize: 262144, iterations: 16, parallelism: 16 } as const; |
| 12 | +const GCM_IV_LENGTH = 12; |
| 13 | +const HKDF_INFO = new TextEncoder().encode('bitgo-v2-session'); |
| 14 | + |
| 15 | +const V2EnvelopeCodec = t.intersection([ |
| 16 | + t.type({ |
| 17 | + v: t.literal(2), |
| 18 | + m: boundedInt(1, ARGON2_MAX.memorySize, 'memorySize'), |
| 19 | + t: boundedInt(1, ARGON2_MAX.iterations, 'iterations'), |
| 20 | + p: boundedInt(1, ARGON2_MAX.parallelism, 'parallelism'), |
| 21 | + salt: base64String, |
| 22 | + iv: base64String, |
| 23 | + ct: base64String, |
| 24 | + }), |
| 25 | + t.partial({ hkdfSalt: base64String, adata: t.string }), |
| 26 | +]); |
| 27 | + |
| 28 | +type V2Envelope = t.TypeOf<typeof V2EnvelopeCodec>; |
| 29 | + |
| 30 | +async function argon2ToAesKey( |
| 31 | + password: string, |
| 32 | + salt: Uint8Array, |
| 33 | + params: { memorySize: number; iterations: number; parallelism: number }, |
| 34 | + usage: KeyUsage |
| 35 | +): Promise<CryptoKey> { |
| 36 | + const keyBytes = await argon2id({ |
| 37 | + password, |
| 38 | + salt, |
| 39 | + ...params, |
| 40 | + hashLength: ARGON2_DEFAULTS.hashLength, |
| 41 | + outputType: 'binary', |
| 42 | + }); |
| 43 | + return subtle.importKey('raw', keyBytes, { name: 'AES-GCM' }, false, [usage]); |
| 44 | +} |
| 45 | + |
| 46 | +async function argon2ToHkdfKey( |
| 47 | + password: string, |
| 48 | + salt: Uint8Array, |
| 49 | + params: { memorySize: number; iterations: number; parallelism: number } |
| 50 | +): Promise<CryptoKey> { |
| 51 | + const keyBytes = await argon2id({ |
| 52 | + password, |
| 53 | + salt, |
| 54 | + ...params, |
| 55 | + hashLength: ARGON2_DEFAULTS.hashLength, |
| 56 | + outputType: 'binary', |
| 57 | + }); |
| 58 | + return subtle.importKey('raw', keyBytes, 'HKDF', false, ['deriveKey']); |
| 59 | +} |
| 60 | + |
| 61 | +function hkdfDeriveAesKey(hkdfKey: CryptoKey, hkdfSalt: Uint8Array, usage: KeyUsage): Promise<CryptoKey> { |
| 62 | + return subtle.deriveKey( |
| 63 | + { name: 'HKDF', hash: 'SHA-256', salt: hkdfSalt, info: HKDF_INFO }, |
| 64 | + hkdfKey, |
| 65 | + { name: 'AES-GCM', length: 256 }, |
| 66 | + false, |
| 67 | + [usage] |
| 68 | + ); |
| 69 | +} |
| 70 | + |
| 71 | +async function aesGcmEncrypt( |
| 72 | + key: CryptoKey, |
| 73 | + iv: Uint8Array, |
| 74 | + plaintext: string, |
| 75 | + adata?: Uint8Array |
| 76 | +): Promise<Uint8Array> { |
| 77 | + const params: AesGcmParams = { name: 'AES-GCM', iv, tagLength: 128 }; |
| 78 | + if (adata) params.additionalData = adata; |
| 79 | + const ct = await subtle.encrypt(params, key, new TextEncoder().encode(plaintext)); |
| 80 | + return new Uint8Array(ct); |
| 81 | +} |
| 82 | + |
| 83 | +async function aesGcmDecrypt(key: CryptoKey, iv: Uint8Array, ct: Uint8Array, adata?: Uint8Array): Promise<string> { |
| 84 | + const params: AesGcmParams = { name: 'AES-GCM', iv, tagLength: 128 }; |
| 85 | + if (adata) params.additionalData = adata; |
| 86 | + const plaintext = await subtle.decrypt(params, key, ct); |
| 87 | + return new TextDecoder().decode(plaintext); |
| 88 | +} |
| 89 | + |
| 90 | +/** Encrypt plaintext using Argon2id KDF + AES-256-GCM. */ |
| 91 | +export async function encryptV2( |
| 92 | + password: string, |
| 93 | + plaintext: string, |
| 94 | + options?: { salt?: Uint8Array; iv?: Uint8Array; memorySize?: number; iterations?: number; parallelism?: number } |
| 95 | +): Promise<string> { |
| 96 | + const memorySize = options?.memorySize ?? ARGON2_DEFAULTS.memorySize; |
| 97 | + const iterations = options?.iterations ?? ARGON2_DEFAULTS.iterations; |
| 98 | + const parallelism = options?.parallelism ?? ARGON2_DEFAULTS.parallelism; |
| 99 | + const salt = options?.salt ?? new Uint8Array(randomBytes(ARGON2_DEFAULTS.saltLength)); |
| 100 | + const iv = options?.iv ?? new Uint8Array(randomBytes(GCM_IV_LENGTH)); |
| 101 | + |
| 102 | + const key = await argon2ToAesKey(password, salt, { memorySize, iterations, parallelism }, 'encrypt'); |
| 103 | + const ct = await aesGcmEncrypt(key, iv, plaintext); |
| 104 | + |
| 105 | + const envelope: V2Envelope = { |
| 106 | + v: 2, |
| 107 | + m: memorySize, |
| 108 | + t: iterations, |
| 109 | + p: parallelism, |
| 110 | + salt: Buffer.from(salt).toString('base64'), |
| 111 | + iv: Buffer.from(iv).toString('base64'), |
| 112 | + ct: Buffer.from(ct).toString('base64'), |
| 113 | + }; |
| 114 | + return JSON.stringify(envelope); |
| 115 | +} |
| 116 | + |
| 117 | +async function decryptV2(password: string, ciphertext: string): Promise<string> { |
| 118 | + const envelope = decodeWithCodec(V2EnvelopeCodec, JSON.parse(ciphertext), 'v2 decrypt: invalid envelope'); |
| 119 | + const salt = new Uint8Array(Buffer.from(envelope.salt, 'base64')); |
| 120 | + const iv = new Uint8Array(Buffer.from(envelope.iv, 'base64')); |
| 121 | + const ct = new Uint8Array(Buffer.from(envelope.ct, 'base64')); |
| 122 | + const params = { memorySize: envelope.m, iterations: envelope.t, parallelism: envelope.p }; |
| 123 | + const adataBytes = envelope.adata ? new TextEncoder().encode(envelope.adata) : undefined; |
| 124 | + |
| 125 | + if (envelope.hkdfSalt) { |
| 126 | + const hkdfKey = await argon2ToHkdfKey(password, salt, params); |
| 127 | + const hkdfSalt = new Uint8Array(Buffer.from(envelope.hkdfSalt, 'base64')); |
| 128 | + const aesKey = await hkdfDeriveAesKey(hkdfKey, hkdfSalt, 'decrypt'); |
| 129 | + return aesGcmDecrypt(aesKey, iv, ct, adataBytes); |
| 130 | + } |
| 131 | + |
| 132 | + const key = await argon2ToAesKey(password, salt, params, 'decrypt'); |
| 133 | + return aesGcmDecrypt(key, iv, ct, adataBytes); |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Auto-detect v1 (SJCL) or v2 (Argon2id + AES-256-GCM) from the envelope `v` field and decrypt. |
| 138 | + */ |
| 139 | +export async function decryptAsync(password: string, ciphertext: string): Promise<string> { |
| 140 | + let envelopeVersion: number | undefined; |
| 141 | + try { |
| 142 | + const envelope = JSON.parse(ciphertext); |
| 143 | + envelopeVersion = envelope.v; |
| 144 | + } catch { |
| 145 | + throw new Error('decrypt: ciphertext is not valid JSON'); |
| 146 | + } |
| 147 | + if (envelopeVersion === 2) { |
| 148 | + return decryptV2(password, ciphertext); |
| 149 | + } |
| 150 | + if (envelopeVersion !== undefined && envelopeVersion !== 1) { |
| 151 | + throw new Error(`decrypt: unknown envelope version ${envelopeVersion}`); |
| 152 | + } |
| 153 | + return sjcl.decrypt(password, ciphertext); |
| 154 | +} |
0 commit comments