|
| 1 | +import { HKDF } from '@stablelib/hkdf' |
| 2 | +import * as x25519 from '@stablelib/x25519' |
| 3 | +import { SHA256, hash } from '@stablelib/sha256' |
| 4 | +import { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305' |
| 5 | +import type { bytes32, bytes } from '../@types/basic.js' |
| 6 | +import type { Hkdf } from '../@types/handshake.js' |
| 7 | +import type { KeyPair } from '../@types/libp2p.js' |
| 8 | +import type { ICryptoInterface } from '../crypto.js' |
| 9 | + |
| 10 | +export const stablelib: ICryptoInterface = { |
| 11 | + hashSHA256 (data: Uint8Array): Uint8Array { |
| 12 | + return hash(data) |
| 13 | + }, |
| 14 | + |
| 15 | + getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf { |
| 16 | + const hkdf = new HKDF(SHA256, ikm, ck) |
| 17 | + const okmU8Array = hkdf.expand(96) |
| 18 | + const okm = okmU8Array |
| 19 | + |
| 20 | + const k1 = okm.slice(0, 32) |
| 21 | + const k2 = okm.slice(32, 64) |
| 22 | + const k3 = okm.slice(64, 96) |
| 23 | + |
| 24 | + return [k1, k2, k3] |
| 25 | + }, |
| 26 | + |
| 27 | + generateX25519KeyPair (): KeyPair { |
| 28 | + const keypair = x25519.generateKeyPair() |
| 29 | + |
| 30 | + return { |
| 31 | + publicKey: keypair.publicKey, |
| 32 | + privateKey: keypair.secretKey |
| 33 | + } |
| 34 | + }, |
| 35 | + |
| 36 | + generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair { |
| 37 | + const keypair = x25519.generateKeyPairFromSeed(seed) |
| 38 | + |
| 39 | + return { |
| 40 | + publicKey: keypair.publicKey, |
| 41 | + privateKey: keypair.secretKey |
| 42 | + } |
| 43 | + }, |
| 44 | + |
| 45 | + generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array { |
| 46 | + return x25519.sharedKey(privateKey, publicKey) |
| 47 | + }, |
| 48 | + |
| 49 | + chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes { |
| 50 | + const ctx = new ChaCha20Poly1305(k) |
| 51 | + |
| 52 | + return ctx.seal(nonce, plaintext, ad) |
| 53 | + }, |
| 54 | + |
| 55 | + chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes | null { |
| 56 | + const ctx = new ChaCha20Poly1305(k) |
| 57 | + |
| 58 | + return ctx.open(nonce, ciphertext, ad) |
| 59 | + } |
| 60 | +} |
0 commit comments