-
-
Notifications
You must be signed in to change notification settings - Fork 228
/
Copy pathencryption.ts
255 lines (229 loc) · 6.99 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import * as nacl from 'tweetnacl';
import * as naclUtil from 'tweetnacl-util';
import { isNullish } from './utils';
export interface EthEncryptedData {
version: string;
nonce: string;
ephemPublicKey: string;
ciphertext: string;
}
/**
* Encrypt a message.
*
* @param options - The encryption options.
* @param options.publicKey - The public key of the message recipient.
* @param options.data - The message data.
* @param options.version - The type of encryption to use.
* @returns The encrypted data.
*/
export function encrypt({
publicKey,
data,
version,
}: {
publicKey: string;
data: unknown;
version: string;
}): EthEncryptedData {
if (isNullish(publicKey)) {
throw new Error('Missing publicKey parameter');
} else if (isNullish(data)) {
throw new Error('Missing data parameter');
} else if (isNullish(version)) {
throw new Error('Missing version parameter');
}
switch (version) {
case 'x25519-xsalsa20-poly1305': {
if (typeof data !== 'string') {
throw new Error('Message data must be given as a string');
}
// generate ephemeral keypair
const ephemeralKeyPair = nacl.box.keyPair();
// assemble encryption parameters - from string to UInt8
let pubKeyUInt8Array;
try {
pubKeyUInt8Array = naclUtil.decodeBase64(publicKey);
} catch (err) {
throw new Error('Bad public key');
}
const msgParamsUInt8Array = naclUtil.decodeUTF8(data);
const nonce = nacl.randomBytes(nacl.box.nonceLength);
// encrypt
const encryptedMessage = nacl.box(
msgParamsUInt8Array,
nonce,
pubKeyUInt8Array,
ephemeralKeyPair.secretKey,
);
// handle encrypted data
const output = {
version: 'x25519-xsalsa20-poly1305',
nonce: naclUtil.encodeBase64(nonce),
ephemPublicKey: naclUtil.encodeBase64(ephemeralKeyPair.publicKey),
ciphertext: naclUtil.encodeBase64(encryptedMessage),
};
// return encrypted msg data
return output;
}
default:
throw new Error('Encryption type/version not supported');
}
}
/**
* Encrypt a message in a way that obscures the message length.
*
* The message is padded to a multiple of 2048 before being encrypted so that the length of the
* resulting encrypted message can't be used to guess the exact length of the original message.
*
* @param options - The encryption options.
* @param options.publicKey - The public key of the message recipient.
* @param options.data - The message data.
* @param options.version - The type of encryption to use.
* @returns The encrypted data.
*/
export function encryptSafely({
publicKey,
data,
version,
}: {
publicKey: string;
data: unknown;
version: string;
}): EthEncryptedData {
if (isNullish(publicKey)) {
throw new Error('Missing publicKey parameter');
} else if (isNullish(data)) {
throw new Error('Missing data parameter');
} else if (isNullish(version)) {
throw new Error('Missing version parameter');
}
const DEFAULT_PADDING_LENGTH = 2 ** 11;
const NACL_EXTRA_BYTES = 16;
if (typeof data === 'object' && 'toJSON' in data) {
// remove toJSON attack vector
// TODO, check all possible children
throw new Error(
'Cannot encrypt with toJSON property. Please remove toJSON property',
);
}
// add padding
const dataWithPadding = {
data,
padding: '',
};
// calculate padding
const dataLength = Buffer.byteLength(
JSON.stringify(dataWithPadding),
'utf-8',
);
const modVal = dataLength % DEFAULT_PADDING_LENGTH;
let padLength = 0;
// Only pad if necessary
if (modVal > 0) {
padLength = DEFAULT_PADDING_LENGTH - modVal - NACL_EXTRA_BYTES; // nacl extra bytes
}
dataWithPadding.padding = '0'.repeat(padLength);
const paddedMessage = JSON.stringify(dataWithPadding);
return encrypt({ publicKey, data: paddedMessage, version });
}
/**
* Decrypt a message.
*
* @param options - The decryption options.
* @param options.encryptedData - The encrypted data.
* @param options.privateKey - The private key to decrypt with.
* @returns The decrypted message.
*/
export function decrypt({
encryptedData,
privateKey,
}: {
encryptedData: EthEncryptedData;
privateKey: string;
}): string {
if (isNullish(encryptedData)) {
throw new Error('Missing encryptedData parameter');
} else if (isNullish(privateKey)) {
throw new Error('Missing privateKey parameter');
}
switch (encryptedData.version) {
case 'x25519-xsalsa20-poly1305': {
// string to buffer to UInt8Array
const recieverPrivateKeyUint8Array = nacl_decodeHex(privateKey);
const recieverEncryptionPrivateKey = nacl.box.keyPair.fromSecretKey(
recieverPrivateKeyUint8Array,
).secretKey;
// assemble decryption parameters
const nonce = naclUtil.decodeBase64(encryptedData.nonce);
const ciphertext = naclUtil.decodeBase64(encryptedData.ciphertext);
const ephemPublicKey = naclUtil.decodeBase64(
encryptedData.ephemPublicKey,
);
// decrypt
const decryptedMessage = nacl.box.open(
ciphertext,
nonce,
ephemPublicKey,
recieverEncryptionPrivateKey,
);
// return decrypted msg data
let output;
try {
output = naclUtil.encodeUTF8(decryptedMessage);
} catch (err) {
throw new Error('Decryption failed.');
}
if (output) {
return output;
}
throw new Error('Decryption failed.');
}
default:
throw new Error('Encryption type/version not supported.');
}
}
/**
* Decrypt a message that has been encrypted using `encryptSafely`.
*
* @param options - The decryption options.
* @param options.encryptedData - The encrypted data.
* @param options.privateKey - The private key to decrypt with.
* @returns The decrypted message.
*/
export function decryptSafely({
encryptedData,
privateKey,
}: {
encryptedData: EthEncryptedData;
privateKey: string;
}): string {
if (isNullish(encryptedData)) {
throw new Error('Missing encryptedData parameter');
} else if (isNullish(privateKey)) {
throw new Error('Missing privateKey parameter');
}
const dataWithPadding = JSON.parse(decrypt({ encryptedData, privateKey }));
return dataWithPadding.data;
}
/**
* Get the encryption public key for the given key.
*
* @param privateKey - The private key to generate the encryption public key with.
* @returns The encryption public key.
*/
export function getEncryptionPublicKey(privateKey: string): string {
const privateKeyUint8Array = nacl_decodeHex(privateKey);
const encryptionPublicKey =
nacl.box.keyPair.fromSecretKey(privateKeyUint8Array).publicKey;
return naclUtil.encodeBase64(encryptionPublicKey);
}
/**
* Convert a hex string to the UInt8Array format used by nacl.
*
* @param msgHex - The string to convert.
* @returns The converted string.
*/
function nacl_decodeHex(msgHex: string): Uint8Array {
const msgBase64 = Buffer.from(msgHex, 'hex').toString('base64');
return naclUtil.decodeBase64(msgBase64);
}