|
1 | 1 | import crypto, { CipherKey } from 'crypto' |
| 2 | +import { ml_kem1024 } from '@noble/post-quantum/ml-kem' |
| 3 | +import { randomBytes } from '@noble/post-quantum/utils' |
2 | 4 | import { StreamMessageAESEncrypted } from '../protocol/StreamMessage' |
3 | 5 | import { StreamrClientError } from '../StreamrClientError' |
4 | 6 | import { GroupKey } from './GroupKey' |
| 7 | +import { AsymmetricEncryptionType } from '@streamr/trackerless-network' |
| 8 | +import { binaryToUtf8 } from '@streamr/utils' |
| 9 | +import { getSubtle } from '../utils/crossPlatformCrypto' |
5 | 10 |
|
6 | 11 | export const INITIALIZATION_VECTOR_LENGTH = 16 |
7 | 12 |
|
| 13 | +const INFO = Buffer.from('streamr-key-exchange') |
| 14 | +const KEM_CIPHER_LENGTH_BYTES = 1568 |
| 15 | +const KDF_SALT_LENGTH_BYTES = 64 |
| 16 | + |
8 | 17 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class |
9 | 18 | export class EncryptionUtil { |
10 | | - private static validateRSAPublicKey(publicKey: crypto.KeyLike): void | never { |
11 | | - const keyString = typeof publicKey === 'string' ? publicKey : publicKey.toString('utf8') |
12 | | - if (typeof keyString !== 'string' || !keyString.startsWith('-----BEGIN PUBLIC KEY-----') |
| 19 | + /** |
| 20 | + * Public API for asymmetric encryption, unified interface across the different AsymmetricEncryptionTypes |
| 21 | + */ |
| 22 | + static async encryptForPublicKey(plaintext: Uint8Array, publicKey: Uint8Array, type: AsymmetricEncryptionType): Promise<Buffer> { |
| 23 | + if (type === AsymmetricEncryptionType.ML_KEM) { |
| 24 | + return this.encryptWithMLKEMPublicKey(plaintext, publicKey) |
| 25 | + } |
| 26 | + if (type === AsymmetricEncryptionType.RSA) { |
| 27 | + return this.encryptWithRSAPublicKey(plaintext, publicKey) |
| 28 | + } |
| 29 | + throw new Error(`Unexpected encryption type: ${type}`) |
| 30 | + } |
| 31 | + |
| 32 | + static async decryptWithPrivateKey(cipher: Uint8Array, privateKey: Uint8Array, type: AsymmetricEncryptionType): Promise<Buffer> { |
| 33 | + if (type === AsymmetricEncryptionType.ML_KEM) { |
| 34 | + return this.decryptWithMLKEMPrivateKey(cipher, privateKey) |
| 35 | + } |
| 36 | + if (type === AsymmetricEncryptionType.RSA) { |
| 37 | + return this.decryptWithRSAPrivateKey(cipher, privateKey) |
| 38 | + } |
| 39 | + throw new Error(`Unexpected encryption type: ${type}`) |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * RSA |
| 44 | + */ |
| 45 | + private static toRSAPublicKeyString(publicKey: Uint8Array): string { |
| 46 | + // RSA publicKey passed around in string format for legacy reasons |
| 47 | + const keyString = binaryToUtf8(publicKey) |
| 48 | + if (!keyString.startsWith('-----BEGIN PUBLIC KEY-----') |
13 | 49 | || !keyString.endsWith('-----END PUBLIC KEY-----\n')) { |
14 | | - throw new Error('"publicKey" must be a PKCS#8 RSA public key in the PEM format') |
| 50 | + throw new Error('"publicKey" must be an RSA public key (SPKI) in PEM format, encoded in UTF-8') |
| 51 | + } |
| 52 | + return keyString |
| 53 | + } |
| 54 | + |
| 55 | + private static toRSAPrivateKeyString(privateKey: Uint8Array): string { |
| 56 | + // RSA privateKey passed around in string format for legacy reasons |
| 57 | + const keyString = binaryToUtf8(privateKey) |
| 58 | + if (!keyString.startsWith('-----BEGIN PRIVATE KEY-----') |
| 59 | + || !keyString.endsWith('-----END PRIVATE KEY-----\n')) { |
| 60 | + throw new Error('"privateKey" must be a PKCS#8 RSA private key in PEM format, encoded in UTF-8') |
15 | 61 | } |
| 62 | + return keyString |
16 | 63 | } |
17 | 64 |
|
18 | | - static encryptWithRSAPublicKey(plaintextBuffer: Uint8Array, publicKey: crypto.KeyLike): Buffer { |
19 | | - this.validateRSAPublicKey(publicKey) |
20 | | - const ciphertextBuffer = crypto.publicEncrypt(publicKey, plaintextBuffer) |
| 65 | + private static encryptWithRSAPublicKey(plaintextBuffer: Uint8Array, publicKey: Uint8Array): Buffer { |
| 66 | + const keyString = this.toRSAPublicKeyString(publicKey) |
| 67 | + const ciphertextBuffer = crypto.publicEncrypt(keyString, plaintextBuffer) |
21 | 68 | return ciphertextBuffer |
22 | 69 | } |
23 | 70 |
|
24 | | - static decryptWithRSAPrivateKey(ciphertext: Uint8Array, privateKey: crypto.KeyLike): Buffer { |
25 | | - return crypto.privateDecrypt(privateKey, ciphertext) |
| 71 | + private static decryptWithRSAPrivateKey(ciphertext: Uint8Array, privateKey: Uint8Array): Buffer { |
| 72 | + const keyString = this.toRSAPrivateKeyString(privateKey) |
| 73 | + return crypto.privateDecrypt(keyString, ciphertext) |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * ML-KEM |
| 78 | + */ |
| 79 | + private static async deriveAESWrapperKey(sharedSecret: Uint8Array, kdfSalt: Uint8Array): Promise<Uint8Array> { |
| 80 | + const subtle = getSubtle() |
| 81 | + const keyMaterial = await subtle.importKey( |
| 82 | + 'raw', |
| 83 | + sharedSecret, |
| 84 | + { name: 'HKDF' }, |
| 85 | + false, |
| 86 | + ['deriveKey'] |
| 87 | + ) |
| 88 | + |
| 89 | + const derivedKey = await subtle.deriveKey( |
| 90 | + { |
| 91 | + name: 'HKDF', |
| 92 | + hash: 'SHA-512', |
| 93 | + salt: kdfSalt, |
| 94 | + info: INFO |
| 95 | + }, |
| 96 | + keyMaterial, |
| 97 | + { name: 'AES-CTR', length: 256 }, |
| 98 | + true, |
| 99 | + ['encrypt', 'decrypt'] |
| 100 | + ) |
| 101 | + |
| 102 | + const exportedKey = await subtle.exportKey('raw', derivedKey) |
| 103 | + return new Uint8Array(exportedKey) |
| 104 | + } |
| 105 | + |
| 106 | + private static async encryptWithMLKEMPublicKey(plaintextBuffer: Uint8Array, publicKey: Uint8Array): Promise<Buffer> { |
| 107 | + // Encapsulate to get kemCipher and shared secret |
| 108 | + // The recipient will be able to derive sharedSecret using privateKey and kemCipher |
| 109 | + const { cipherText: kemCipher, sharedSecret } = ml_kem1024.encapsulate(publicKey) |
| 110 | + |
| 111 | + if (kemCipher.length !== KEM_CIPHER_LENGTH_BYTES) { |
| 112 | + throw new Error(`Expected KEM cipher to be ${KEM_CIPHER_LENGTH_BYTES}, but it was ${kemCipher.length} bytes`) |
| 113 | + } |
| 114 | + |
| 115 | + // Derive an AES wrapping key from the shared secret using HKDF |
| 116 | + // The recipient will be able to repeat this computation to derive the same key |
| 117 | + const kdfSalt = randomBytes(KDF_SALT_LENGTH_BYTES) |
| 118 | + const wrappingAESKey = await this.deriveAESWrapperKey(sharedSecret, kdfSalt) |
| 119 | + |
| 120 | + // Encrypt plaintext with the AES wrapping key |
| 121 | + const aesEncryptedPlaintext = this.encryptWithAES(plaintextBuffer, Buffer.from(wrappingAESKey)) |
| 122 | + |
| 123 | + // Concatenate the deliverables into a binary package |
| 124 | + return Buffer.concat([kemCipher, kdfSalt, aesEncryptedPlaintext]) |
| 125 | + } |
| 126 | + |
| 127 | + private static async decryptWithMLKEMPrivateKey(cipherPackage: Uint8Array, privateKey: Uint8Array): Promise<Buffer> { |
| 128 | + // Split the cipherPackage, see encryptWithMLKEMPublicKey how it's constructed |
| 129 | + let pos = 0 |
| 130 | + const kemCipher = cipherPackage.slice(0, KEM_CIPHER_LENGTH_BYTES) |
| 131 | + pos += KEM_CIPHER_LENGTH_BYTES |
| 132 | + const kdfSalt = cipherPackage.slice(pos, pos + KDF_SALT_LENGTH_BYTES) |
| 133 | + pos += KDF_SALT_LENGTH_BYTES |
| 134 | + const aesEncryptedPlaintext = cipherPackage.slice(pos) |
| 135 | + |
| 136 | + // Derive the shared secret using the private key and kemCipher |
| 137 | + const sharedSecret = ml_kem1024.decapsulate(kemCipher, privateKey) |
| 138 | + |
| 139 | + // Derive the wrappingAESKey |
| 140 | + const wrappingAESKey = await this.deriveAESWrapperKey(sharedSecret, kdfSalt) |
| 141 | + |
| 142 | + // Decrypt the aesEncryptedPlaintext |
| 143 | + return this.decryptWithAES(aesEncryptedPlaintext, Buffer.from(wrappingAESKey)) |
26 | 144 | } |
27 | 145 |
|
28 | 146 | /* |
|
0 commit comments