Skip to content

Instantly share code, notes, and snippets.

@thomaskonrad
Created February 8, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaskonrad/c8ed4d73bb200ecc9ecdf5b85e2eb7f0 to your computer and use it in GitHub Desktop.
Save thomaskonrad/c8ed4d73bb200ecc9ecdf5b85e2eb7f0 to your computer and use it in GitHub Desktop.
Authenticated Secret Key Cryptography (AEAD) in TypeScript
export default class AuthenticatedSecretKeyCryptography {
public static readonly KEY_LENGTH_IN_BYTES = 16;
public static readonly IV_LENGTH_IN_BYTES = 16;
public static readonly TAG_LENGTH_IN_BYTES = 16;
private static readonly ALGORITHM = 'AES-GCM';
private readonly secretKey: CryptoKey;
private readonly tagLengthInBytes: number;
public constructor(secretKey: CryptoKey, tagLengthInBytes = AuthenticatedSecretKeyCryptography.TAG_LENGTH_IN_BYTES) {
this.secretKey = secretKey;
this.tagLengthInBytes = tagLengthInBytes;
}
public static async getCryptoKeyFromRawKey(rawKey: Uint8Array): Promise<CryptoKey> {
// @ts-ignore
return await crypto.subtle.importKey(
'raw',
rawKey,
{
name: this.ALGORITHM,
},
true,
['encrypt', 'decrypt'],
);
}
public async encrypt(iv: Uint8Array, data: Uint8Array): Promise<ArrayBuffer> {
return await crypto.subtle.encrypt({
name: AuthenticatedSecretKeyCryptography.ALGORITHM,
iv,
tagLength: this.tagLengthInBytes * 8,
},
this.secretKey,
data,
);
}
public async decrypt(iv: Uint8Array, data: Uint8Array): Promise<ArrayBuffer> {
return await crypto.subtle.decrypt({
name: AuthenticatedSecretKeyCryptography.ALGORITHM,
iv,
tagLength: this.tagLengthInBytes * 8,
},
this.secretKey,
data,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment