import crypto from 'crypto' ; import { promisify } from 'util' ; import errcode from 'err-code' ; import randomBytes from '../random-bytes.js' ; import * as utils from './rsa-utils.js' ; import type { JWKKeyPair } from './interface.js' ; const keypair = promisify ( crypto . generateKeyPair ) ; export { utils } ; export async function generateKey ( bits ) { const key = await keypair ( 'rsa' , { modulusLength : bits , publicKeyEncoding : { type : 'pkcs1' , format : 'jwk' } , privateKeyEncoding : { type : 'pkcs1' , format : 'jwk' } } ) ; return { privateKey : key . privateKey , publicKey : key . publicKey } ; } export async function unmarshalPrivateKey ( key ) { if ( key == null ) { throw errcode ( new Error ( 'Missing key parameter' ) , 'ERR_MISSING_KEY' ) ; } return { privateKey : key , publicKey : { kty : key . kty , n : key . n , e : key . e } } ; } export { randomBytes as getRandomValues } ; export async function hashAndSign ( key , msg ) { return crypto . createSign ( 'RSA-SHA256' ) . update ( msg ) . sign ( { format : 'jwk' , key } ) ; } export async function hashAndVerify ( key , sig , msg ) { return crypto . createVerify ( 'RSA-SHA256' ) . update ( msg ) . verify ( { format : 'jwk' , key } , sig ) ; } const padding = crypto . constants . RSA_PKCS1_PADDING ; export function encrypt ( key , bytes ) { return crypto . publicEncrypt ( { format : 'jwk' , key , padding } , bytes ) ; } export function decrypt ( key , bytes ) { return crypto . privateDecrypt ( { format : 'jwk' , key , padding } , bytes ) ; }