import { expect } from 'chai' ; import { keys } from 'libp2p-crypto' ; import type { Private , Public } from './identity' ; import { PrivateKey , PublicKey } from './keypair' ; import { decrypt , encrypt } from './utils' ; describe ( 'Keypair' , ( ) => { it ( 'should support libp2p keys that match our interfaces' , async ( ) => { const ed25519 = await keys . generateKeyPair ( 'Ed25519' , 256 ) ; const rsa = await keys . generateKeyPair ( 'RSA' , 512 ) ; expect ( ed25519 . sign ) . to . not . be . undefined ; expect ( rsa . sign ) . to . not . be . undefined ; const edPublic = ed25519 . public ; expect ( edPublic . verify ) . to . not . be . undefined ; const rsaPublic = rsa . public ; expect ( rsaPublic . verify ) . to . not . be . undefined ; } ) ; it ( 'should be able to serialize and recover identities' , async ( ) => { const id = PrivateKey . fromRandom ( ) ; const str = id . toString ( ) ; const back = PrivateKey . fromString ( str ) ; expect ( id ) . to . deep . equal ( back ) ; } ) ; describe ( 'Signatures' , ( ) => { it ( 'should be able to verify signature' , async ( ) => { const id = PrivateKey . fromRandom ( ) ; const msg = new TextEncoder ( ) . encode ( 'teststring' ) ; const sig = await id . sign ( msg ) ; const verify = await id . public . verify ( msg , sig ) ; expect ( verify ) . to . be . true ; } ) ; } ) ; describe ( 'Encryption' , ( ) => { const id = PrivateKey . fromRandom ( ) ; it ( 'should be able to encrypt/decrypt using keypair/identity' , async ( ) => { const msg = new TextEncoder ( ) . encode ( 'teststring' ) ; const ciphertext = await id . public . encrypt ( msg ) ; const plaintext = await id . decrypt ( ciphertext ) ; expect ( plaintext ) . to . deep . equal ( msg ) ; } ) ; it ( 'should be able to encrypt/decrypt using separate keys' , async ( ) => { const privKey = PrivateKey . fromRandom ( ) ; const publicKey = privKey . public . toString ( ) ; const msg = new TextEncoder ( ) . encode ( 'howdy!' ) ; const pubKey = PublicKey . fromString ( publicKey ) ; const ciphertext = await encrypt ( msg , pubKey . pubKey ) ; const plaintext = await decrypt ( ciphertext , privKey . privKey ) ; expect ( plaintext ) . to . deep . equal ( msg ) ; } ) ; it ( 'should be able to encrypt/decrypt using classes' , async ( ) => { const privKey = PrivateKey . fromRandom ( ) ; const publicKey = privKey . public . toString ( ) ; const msg = new TextEncoder ( ) . encode ( 'howdy!' ) ; const pubKey = PublicKey . fromString ( publicKey ) ; const ciphertext = await pubKey . encrypt ( msg ) ; const plaintext = await privKey . decrypt ( ciphertext ) ; expect ( plaintext ) . to . deep . equal ( msg ) ; } ) ; } ) ; } ) ;