|
| 1 | +import { SodiumPlus, X25519PublicKey, X25519SecretKey, CryptographyKey } from 'sodium-plus'; |
| 2 | + |
| 3 | +let sodium: SodiumPlus; |
| 4 | + |
| 5 | +export class Session { |
| 6 | + // Encoding for the key exchange, no requirements to be small |
| 7 | + protected readonly stringFormatKey: BufferEncoding = 'base64'; |
| 8 | + |
| 9 | + // Encoding for the transfer of encrypted data, should be smaller as possible |
| 10 | + protected readonly stringFormatEncryptedData: BufferEncoding = 'base64'; |
| 11 | + |
| 12 | + // Encoding before the encryption to keep unicode chars |
| 13 | + protected readonly stringFormatRawData: BufferEncoding = 'base64'; |
| 14 | + |
| 15 | + protected decryptKey: CryptographyKey; |
| 16 | + |
| 17 | + protected encryptKey: CryptographyKey; |
| 18 | + |
| 19 | + protected secretKey: X25519SecretKey; |
| 20 | + |
| 21 | + public publicKey: X25519PublicKey; |
| 22 | + |
| 23 | + async sodium(): Promise<SodiumPlus> { |
| 24 | + return sodium || SodiumPlus.auto(); |
| 25 | + } |
| 26 | + |
| 27 | + get publicKeyString(): string { |
| 28 | + return this.publicKey.toString(this.stringFormatKey); |
| 29 | + } |
| 30 | + |
| 31 | + publicKeyFromString(text: string): X25519PublicKey { |
| 32 | + return new X25519PublicKey(Buffer.from(text, this.stringFormatKey)); |
| 33 | + } |
| 34 | + |
| 35 | + async encryptToBuffer(plaintext: string | Buffer): Promise<Buffer> { |
| 36 | + const sodium = await this.sodium(); |
| 37 | + const nonce = await sodium.randombytes_buf(24); |
| 38 | + |
| 39 | + const ciphertext = await sodium.crypto_secretbox( |
| 40 | + Buffer.from(plaintext).toString(this.stringFormatRawData), |
| 41 | + nonce, |
| 42 | + this.encryptKey, |
| 43 | + ); |
| 44 | + |
| 45 | + return Buffer.concat([nonce, ciphertext]); |
| 46 | + } |
| 47 | + |
| 48 | + async encrypt(plaintext: string | Buffer): Promise<string> { |
| 49 | + const buffer = await this.encryptToBuffer(plaintext); |
| 50 | + return buffer.toString(this.stringFormatEncryptedData); |
| 51 | + } |
| 52 | + |
| 53 | + async decryptToBuffer(data: string | Buffer): Promise<Buffer> { |
| 54 | + const sodium = await this.sodium(); |
| 55 | + const buffer = Buffer.from(Buffer.isBuffer(data) ? data.toString() : data, this.stringFormatEncryptedData); |
| 56 | + |
| 57 | + const decrypted = await sodium.crypto_secretbox_open( |
| 58 | + buffer.slice(24), |
| 59 | + buffer.slice(0, 24), |
| 60 | + this.decryptKey, |
| 61 | + ); |
| 62 | + |
| 63 | + return Buffer.from(decrypted.toString(), this.stringFormatRawData); |
| 64 | + } |
| 65 | + |
| 66 | + async decrypt(data: string | Buffer): Promise<string> { |
| 67 | + const buffer = await this.decryptToBuffer(data); |
| 68 | + return buffer.toString(); |
| 69 | + } |
| 70 | +} |
0 commit comments