import 'node-forge/lib/asn1.js' ; import 'node-forge/lib/rsa.js' ; import forge from 'node-forge/lib/forge.js' ; import { bigIntegerToUintBase64url , base64urlToBigInteger } from './../util.js' ; import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' ; import { toString as uint8ArrayToString } from 'uint8arrays/to-string' ; import errcode from 'err-code' ; export function pkcs1ToJwk ( bytes ) { const asn1 = forge . asn1 . fromDer ( uint8ArrayToString ( bytes , 'ascii' ) ) ; const privateKey = forge . pki . privateKeyFromAsn1 ( asn1 ) ; return { kty : 'RSA' , n : bigIntegerToUintBase64url ( privateKey . n ) , e : bigIntegerToUintBase64url ( privateKey . e ) , d : bigIntegerToUintBase64url ( privateKey . d ) , p : bigIntegerToUintBase64url ( privateKey . p ) , q : bigIntegerToUintBase64url ( privateKey . q ) , dp : bigIntegerToUintBase64url ( privateKey . dP ) , dq : bigIntegerToUintBase64url ( privateKey . dQ ) , qi : bigIntegerToUintBase64url ( privateKey . qInv ) , alg : 'RS256' } ; } export function jwkToPkcs1 ( jwk ) { if ( jwk . n == null || jwk . e == null || jwk . d == null || jwk . p == null || jwk . q == null || jwk . dp == null || jwk . dq == null || jwk . qi == null ) { throw errcode ( new Error ( 'JWK was missing components' ) , 'ERR_INVALID_PARAMETERS' ) ; } const asn1 = forge . pki . privateKeyToAsn1 ( { n : base64urlToBigInteger ( jwk . n ) , e : base64urlToBigInteger ( jwk . e ) , d : base64urlToBigInteger ( jwk . d ) , p : base64urlToBigInteger ( jwk . p ) , q : base64urlToBigInteger ( jwk . q ) , dP : base64urlToBigInteger ( jwk . dp ) , dQ : base64urlToBigInteger ( jwk . dq ) , qInv : base64urlToBigInteger ( jwk . qi ) } ) ; return uint8ArrayFromString ( forge . asn1 . toDer ( asn1 ) . getBytes ( ) , 'ascii' ) ; } export function pkixToJwk ( bytes ) { const asn1 = forge . asn1 . fromDer ( uint8ArrayToString ( bytes , 'ascii' ) ) ; const publicKey = forge . pki . publicKeyFromAsn1 ( asn1 ) ; return { kty : 'RSA' , n : bigIntegerToUintBase64url ( publicKey . n ) , e : bigIntegerToUintBase64url ( publicKey . e ) } ; } export function jwkToPkix ( jwk ) { if ( jwk . n == null || jwk . e == null ) { throw errcode ( new Error ( 'JWK was missing components' ) , 'ERR_INVALID_PARAMETERS' ) ; } const asn1 = forge . pki . publicKeyToAsn1 ( { n : base64urlToBigInteger ( jwk . n ) , e : base64urlToBigInteger ( jwk . e ) } ) ; return uint8ArrayFromString ( forge . asn1 . toDer ( asn1 ) . getBytes ( ) , 'ascii' ) ; }