-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.ts
66 lines (55 loc) · 1.6 KB
/
encryption.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {
RawAesKeyringNode,
buildClient,
CommitmentPolicy,
RawAesWrappingSuiteIdentifier,
} from '@aws-crypto/client-node';
import { TextEncoder } from 'util';
import {
ENCRYPTION_WRAPPING_KEY,
ENCRYPTION_KEY_NAME,
ENCRYPTION_KEY_NAMESPACE,
} from './secrets';
const encoder = new TextEncoder();
const keyName = ENCRYPTION_KEY_NAME;
const keyNamespace = ENCRYPTION_KEY_NAMESPACE;
const unencryptedMasterKey = encoder.encode(ENCRYPTION_WRAPPING_KEY);
const wrappingSuite =
RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING;
const keyRing = new RawAesKeyringNode({
keyName,
keyNamespace,
unencryptedMasterKey,
wrappingSuite,
});
const encryptionClient = buildClient(
CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
);
const context = {
purpose: 'Gov.UK Cognito -> Postgres Migration',
};
export async function encrypt(cleartext: string) {
const { result } = await encryptionClient.encrypt(keyRing, cleartext, {
encryptionContext: context,
});
const cipherText = b64Encode(result);
return cipherText;
}
export async function decrypt(cipherText: string) {
const { plaintext, messageHeader } = await encryptionClient.decrypt(
keyRing,
b64Decode(cipherText)
);
const { encryptionContext } = messageHeader;
Object.entries(context).forEach(([key, value]) => {
if (encryptionContext[key] !== value)
throw new Error('Encryption Context does not match expected values');
});
return plaintext.toString();
}
function b64Encode(buff: Buffer) {
return buff.toString('base64');
}
function b64Decode(str: string) {
return Buffer.from(str, 'base64');
}