2021-03-24 00:50:02 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
import crypto from 'crypto';
|
|
|
|
|
|
|
|
import { typedArrayToArrayBuffer as toArrayBuffer } from '../Crypto';
|
|
|
|
|
|
|
|
export function sign(key: ArrayBuffer, data: ArrayBuffer): ArrayBuffer {
|
|
|
|
return toArrayBuffer(
|
|
|
|
crypto
|
|
|
|
.createHmac('sha256', Buffer.from(key))
|
|
|
|
.update(Buffer.from(data))
|
|
|
|
.digest()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-04-07 21:27:40 +00:00
|
|
|
export enum HashType {
|
|
|
|
size256 = 'sha256',
|
|
|
|
size512 = 'sha512',
|
|
|
|
}
|
|
|
|
|
|
|
|
export function hash(type: HashType, data: ArrayBuffer): ArrayBuffer {
|
2021-03-24 00:50:02 +00:00
|
|
|
return toArrayBuffer(
|
2021-04-07 21:27:40 +00:00
|
|
|
crypto.createHash(type).update(Buffer.from(data)).digest()
|
2021-03-24 00:50:02 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-04-02 22:33:07 +00:00
|
|
|
export enum CipherType {
|
|
|
|
AES256CBC = 'aes-256-cbc',
|
|
|
|
AES256CTR = 'aes-256-ctr',
|
|
|
|
}
|
|
|
|
|
2021-03-24 00:50:02 +00:00
|
|
|
export function encrypt(
|
|
|
|
key: ArrayBuffer,
|
|
|
|
data: ArrayBuffer,
|
2021-04-02 22:33:07 +00:00
|
|
|
iv: ArrayBuffer,
|
|
|
|
cipherType: CipherType = CipherType.AES256CBC
|
2021-03-24 00:50:02 +00:00
|
|
|
): ArrayBuffer {
|
|
|
|
const cipher = crypto.createCipheriv(
|
2021-04-02 22:33:07 +00:00
|
|
|
cipherType,
|
2021-03-24 00:50:02 +00:00
|
|
|
Buffer.from(key),
|
|
|
|
Buffer.from(iv)
|
|
|
|
);
|
|
|
|
const encrypted = Buffer.concat([
|
|
|
|
cipher.update(Buffer.from(data)),
|
|
|
|
cipher.final(),
|
|
|
|
]);
|
|
|
|
|
|
|
|
return toArrayBuffer(encrypted);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function decrypt(
|
|
|
|
key: ArrayBuffer,
|
|
|
|
data: ArrayBuffer,
|
2021-04-02 22:33:07 +00:00
|
|
|
iv: ArrayBuffer,
|
|
|
|
cipherType: CipherType = CipherType.AES256CBC
|
2021-03-24 00:50:02 +00:00
|
|
|
): ArrayBuffer {
|
|
|
|
const cipher = crypto.createDecipheriv(
|
2021-04-02 22:33:07 +00:00
|
|
|
cipherType,
|
2021-03-24 00:50:02 +00:00
|
|
|
Buffer.from(key),
|
|
|
|
Buffer.from(iv)
|
|
|
|
);
|
|
|
|
const decrypted = Buffer.concat([
|
|
|
|
cipher.update(Buffer.from(data)),
|
|
|
|
cipher.final(),
|
|
|
|
]);
|
|
|
|
|
|
|
|
return toArrayBuffer(decrypted);
|
|
|
|
}
|