import * as crypto from 'crypto' ; import { encrypt as pkcs7Encrypt } from './pkcs7' ; export type CipherEncrypt = ( message : string , receiveId ? : string ) => string ; export const createCipherEncrypt = ( { aesKey , iv } ) : CipherEncrypt => ( message , receiveId = '' ) => { const random = crypto . randomBytes ( 16 ) ; const messageLength = Buffer . alloc ( 4 ) ; messageLength . writeUIntBE ( message . length , 0 , 4 ) ; const messageBuffer = Buffer . from ( message ) ; const receiveIdBuffer = Buffer . from ( receiveId ) ; const plainMessage = pkcs7Encrypt ( Buffer . concat ( [ random , messageLength , messageBuffer , receiveIdBuffer ] ) ) ; const decipher = crypto . createCipheriv ( 'aes-256-cbc' , aesKey , iv ) . setAutoPadding ( false ) ; const aesEncryptedMessage = Buffer . concat ( [ decipher . update ( plainMessage ) , decipher . final ( ) , ] ) ; const base64EncodedMessage = aesEncryptedMessage . toString ( 'base64' ) ; return base64EncodedMessage ; } ;