Use browser (subtle) implementation for all env

This commit is contained in:
Franck Royer 2022-03-07 07:48:02 +11:00
parent 2e816918c3
commit 9dae5168fc
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
2 changed files with 34 additions and 35 deletions

View File

@ -1,38 +1,37 @@
export const SymmetricKeySize = 32;
import { randomBytes, subtle } from "../../crypto";
export const KeySize = 32;
export const IvSize = 12;
export const TagSize = 16;
export interface Symmetric {
/**
* Proceed with symmetric encryption of `clearText` value.
*/
encrypt: (
iv: Buffer | Uint8Array,
key: Buffer,
clearText: Buffer
) => Promise<Buffer>;
/**
* Proceed with symmetric decryption of `cipherText` value.
*/
decrypt: (iv: Buffer, key: Buffer, cipherText: Buffer) => Promise<Buffer>;
/**
* Generate an Initialization Vector (iv) for for Symmetric encryption purposes.
*/
generateIv: () => Uint8Array;
const Algorithm = { name: "AES-GCM", length: 128 };
export async function encrypt(
iv: Buffer | Uint8Array,
key: Buffer,
clearText: Buffer
): Promise<Buffer> {
return subtle
.importKey("raw", key, Algorithm, false, ["encrypt"])
.then((cryptoKey) =>
subtle.encrypt({ iv, ...Algorithm }, cryptoKey, clearText)
)
.then(Buffer.from);
}
export let symmetric: Symmetric = {} as unknown as Symmetric;
export async function decrypt(
iv: Buffer,
key: Buffer,
cipherText: Buffer
): Promise<Buffer> {
return subtle
.importKey("raw", key, Algorithm, false, ["decrypt"])
.then((cryptoKey) =>
subtle.decrypt({ iv, ...Algorithm }, cryptoKey, cipherText)
)
.then(Buffer.from);
}
import("./browser")
.then((mod) => {
symmetric = mod;
})
.catch((eBrowser) => {
import("./node")
.then((mod) => {
symmetric = mod;
})
.catch((eNode) => {
throw `Could not load any symmetric crypto modules: ${eBrowser}, ${eNode}`;
});
});
export function generateIv(): Uint8Array {
return randomBytes(IvSize);
}

View File

@ -7,7 +7,7 @@ import * as secp256k1 from "secp256k1";
import { hexToBytes } from "../utils";
import * as ecies from "./ecies";
import { IvSize, symmetric, SymmetricKeySize } from "./symmetric";
import * as symmetric from "./symmetric";
const FlagsLength = 1;
const FlagMask = 3; // 0011
@ -170,7 +170,7 @@ export async function decryptSymmetric(
key: Uint8Array | Buffer | string
): Promise<Uint8Array> {
const data = Buffer.from(payload);
const ivStart = data.length - IvSize;
const ivStart = data.length - symmetric.IvSize;
const cipher = data.slice(0, ivStart);
const iv = data.slice(ivStart);
@ -190,7 +190,7 @@ export function generatePrivateKey(): Uint8Array {
* Generate a new symmetric key to be used for symmetric encryption.
*/
export function generateSymmetricKey(): Uint8Array {
return randomBytes(SymmetricKeySize);
return randomBytes(symmetric.KeySize);
}
/**