-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathcrypto.ts
More file actions
270 lines (237 loc) · 9.74 KB
/
crypto.ts
File metadata and controls
270 lines (237 loc) · 9.74 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
'use strict';
import Logger from '../../../../common/lib/util/logger';
import crypto from 'crypto';
import ErrorInfo from '../../../../common/lib/types/errorinfo';
import * as API from '../../../../../ably';
import ICryptoStatic, { IGetCipherParams } from '../../../../common/types/ICryptoStatic';
import ICipher from '../../../../common/types/ICipher';
import { CryptoDataTypes } from '../../../../common/types/cryptoDataTypes';
import { Cipher as NodeCipher, CipherKey as NodeCipherKey } from 'crypto';
import BufferUtils, { Bufferlike, Output as BufferUtilsOutput } from './bufferutils';
import util from 'util';
// The type to which ably-forks/msgpack-js deserializes elements of the `bin` or `ext` type
type MessagePackBinaryType = Buffer;
type IV = CryptoDataTypes.IV<BufferUtilsOutput>;
type InputPlaintext = CryptoDataTypes.InputPlaintext<Bufferlike, BufferUtilsOutput>;
type OutputCiphertext = Buffer;
type InputCiphertext = CryptoDataTypes.InputCiphertext<MessagePackBinaryType, BufferUtilsOutput>;
type OutputPlaintext = Buffer;
var createCryptoClass = function (bufferUtils: typeof BufferUtils) {
var DEFAULT_ALGORITHM = 'aes';
var DEFAULT_KEYLENGTH = 256; // bits
var DEFAULT_MODE = 'cbc';
var DEFAULT_BLOCKLENGTH = 16; // bytes
/**
* Internal: generate a buffer of secure random bytes of the given length
* @param bytes
*/
async function generateRandom(bytes: number): Promise<Buffer> {
return util.promisify(crypto.randomBytes)(bytes);
}
/**
* Internal: calculate the padded length of a given plaintext
* using PKCS5.
* @param plaintextLength
* @return
*/
function getPaddedLength(plaintextLength: number) {
return (plaintextLength + DEFAULT_BLOCKLENGTH) & -DEFAULT_BLOCKLENGTH;
}
/**
* Internal: checks that the cipherParams are a valid combination. Currently
* just checks that the calculated keyLength is a valid one for aes-cbc
*/
function validateCipherParams(params: API.CipherParams) {
if (params.algorithm === 'aes' && params.mode === 'cbc') {
if (params.keyLength === 128 || params.keyLength === 256) {
return;
}
throw new Error(
'Unsupported key length ' +
params.keyLength +
' for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)',
);
}
}
function normaliseBase64(string: string) {
/* url-safe base64 strings use _ and - instread of / and + */
return string.replace('_', '/').replace('-', '+');
}
/**
* Internal: obtain the pkcs5 padding string for a given padded length;
*/
function filledBuffer(length: number, value: number) {
var result = Buffer.alloc(length);
result.fill(value);
return result;
}
var pkcs5Padding = [filledBuffer(16, 16)];
for (var i = 1; i <= 16; i++) pkcs5Padding.push(filledBuffer(i, i));
/**
* A class encapsulating the client-specifiable parameters for
* the cipher.
*
* algorithm is the name of the algorithm in the default system provider,
* or the lower-cased version of it; eg "aes" or "AES".
*
* Clients may instance a CipherParams directly and populate it, or may
* query the implementation to obtain a default system CipherParams.
*/
class CipherParams implements API.CipherParams {
algorithm: string;
keyLength: number;
mode: string;
key: NodeCipherKey;
iv: unknown;
constructor(algorithm: string, keyLength: number, mode: string, key: NodeCipherKey) {
this.algorithm = algorithm;
this.keyLength = keyLength;
this.mode = mode;
this.key = key;
this.iv = null;
}
}
function isInstCipherParams(params: API.CipherParams | API.CipherParamOptions): params is API.CipherParams {
/* In node, can't use instanceof CipherParams due to the vm context problem (see
* https://github.com/nwjs/nw.js/wiki/Differences-of-JavaScript-contexts).
* So just test for presence of all necessary attributes */
return !!(params.algorithm && params.key && params.keyLength && params.mode);
}
/**
* Utility classes and interfaces for message payload encryption.
*
* This class supports AES/CBC/PKCS5 with a default keylength of 128 bits
* but supporting other keylengths. Other algorithms and chaining modes are
* not supported directly, but supportable by extending/implementing the base
* classes and interfaces here.
*
* Secure random data for creation of Initialization Vectors (IVs) and keys
* is obtained from the default system SecureRandom. Future extensions of this
* class might make the SecureRandom pluggable or at least seedable with
* client-provided entropy.
*
* Each message payload is encrypted with an IV in CBC mode, and the IV is
* concatenated with the resulting raw ciphertext to construct the "ciphertext"
* data passed to the recipient.
*/
class Crypto {
static CipherParams = CipherParams;
/**
* Obtain a complete CipherParams instance from the provided params, filling
* in any not provided with default values, calculating a keyLength from
* the supplied key, and validating the result.
* @param params an object containing at a minimum a `key` key with value the
* key, as either a binary or a base64-encoded string.
* May optionally also contain: algorithm (defaults to AES),
* mode (defaults to 'cbc')
*/
static getDefaultParams(params: API.CipherParamOptions) {
var key: NodeCipherKey;
if (!params.key) {
throw new Error('Crypto.getDefaultParams: a key is required');
}
if (typeof params.key === 'string') {
key = bufferUtils.base64Decode(normaliseBase64(params.key));
} else if (params.key instanceof ArrayBuffer) {
key = Buffer.from(params.key);
} else {
key = params.key;
}
var algorithm = params.algorithm || DEFAULT_ALGORITHM;
var keyLength = key.length * 8;
var mode = params.mode || DEFAULT_MODE;
var cipherParams = new CipherParams(algorithm, keyLength, mode, key);
if (params.keyLength && params.keyLength !== cipherParams.keyLength) {
throw new Error(
'Crypto.getDefaultParams: a keyLength of ' +
params.keyLength +
' was specified, but the key actually has length ' +
cipherParams.keyLength,
);
}
validateCipherParams(cipherParams);
return cipherParams;
}
/**
* Generate a random encryption key from the supplied keylength (or the
* default keyLength if none supplied) as a Buffer
* @param keyLength (optional) the required keyLength in bits
*/
static async generateRandomKey(keyLength?: number): Promise<API.CipherKey> {
try {
return generateRandom((keyLength || DEFAULT_KEYLENGTH) / 8);
} catch (err) {
// ably-os:inline-error-update:50000:2025-08-22:e8u Original: "Failed to generate random key: {error message}"
throw new ErrorInfo('Failed to generate random key: ' + (err as Error).message, 50000, 500, err as Error);
}
}
/**
* Internal; get a ChannelCipher instance based on the given cipherParams
* @param params either a CipherParams instance or some subset of its
* fields that includes a key
*/
static getCipher(params: IGetCipherParams<IV>, logger: Logger) {
var cipherParams = isInstCipherParams(params) ? (params as CipherParams) : this.getDefaultParams(params);
return {
cipherParams: cipherParams,
cipher: new CBCCipher(cipherParams, params.iv ?? null, logger),
};
}
}
Crypto satisfies ICryptoStatic<IV, InputPlaintext, OutputCiphertext, InputCiphertext, OutputPlaintext>;
class CBCCipher implements ICipher<InputPlaintext, OutputCiphertext, InputCiphertext, OutputPlaintext> {
algorithm: string;
key: NodeCipherKey;
iv: Buffer | null;
encryptCipher: NodeCipher | null = null;
constructor(
params: CipherParams,
iv: Buffer | null,
private readonly logger: Logger,
) {
this.algorithm = params.algorithm + '-' + String(params.keyLength) + '-' + params.mode;
this.key = params.key;
this.iv = iv;
}
async encrypt(plaintext: InputPlaintext): Promise<OutputCiphertext> {
Logger.logAction(this.logger, Logger.LOG_MICRO, 'CBCCipher.encrypt()', '');
const iv = await this.getIv();
if (!this.encryptCipher) {
this.encryptCipher = crypto.createCipheriv(this.algorithm, this.key, iv);
}
var plaintextBuffer = bufferUtils.toBuffer(plaintext);
var plaintextLength = plaintextBuffer.length,
paddedLength = getPaddedLength(plaintextLength);
var cipherOut = this.encryptCipher.update(
Buffer.concat([plaintextBuffer, pkcs5Padding[paddedLength - plaintextLength]]),
);
var ciphertext = Buffer.concat([iv, cipherOut]);
return ciphertext;
}
async decrypt(ciphertext: InputCiphertext): Promise<OutputPlaintext> {
var decryptCipher = crypto.createDecipheriv(this.algorithm, this.key, ciphertext.slice(0, DEFAULT_BLOCKLENGTH)),
plaintext = decryptCipher.update(ciphertext.slice(DEFAULT_BLOCKLENGTH)),
final = decryptCipher.final();
if (final && final.length) plaintext = Buffer.concat([plaintext, final]);
return plaintext;
}
async getIv(): Promise<Buffer> {
if (this.iv) {
var iv = this.iv;
this.iv = null;
return iv;
}
var randomBlock = await generateRandom(DEFAULT_BLOCKLENGTH);
if (!this.encryptCipher) {
return randomBlock;
} else {
/* Since the iv for a new block is the ciphertext of the last, this
* sets a new iv (= aes(randomBlock XOR lastCipherText)) as well as
* returning it */
return this.encryptCipher.update(randomBlock);
}
}
}
return Crypto;
};
export { createCryptoClass };