@@ -39,7 +39,7 @@ function JweCrypto(config) {
3939 "enc" : "A256GCM"
4040 } ;
4141
42- const encodedJweHeader = Buffer . from ( utils . toEncodedString ( JSON . stringify ( jweHeader ) , 'binary ', 'base64url' ) ) ;
42+ const encodedJweHeader = toEncodedString ( JSON . stringify ( jweHeader ) , 'utf8 ', 'base64url' ) ;
4343
4444 const secretKey = nodeCrypto . randomBytes ( 32 ) ;
4545 const secretKeyBuffer = Buffer . from ( secretKey , 'binary' ) ;
@@ -61,10 +61,10 @@ function JweCrypto(config) {
6161 cipherText += cipher . final ( 'base64' ) ;
6262 const authTag = cipher . getAuthTag ( ) . toString ( "base64" ) ;
6363
64- const encodedEncryptedSecretKey = utils . toEncodedString ( encryptedSecretKey , 'binary' , 'base64url' ) ;
65- const encodedIv = utils . toEncodedString ( iv , 'binary' , 'base64url' ) ;
66- const encodedEncryptedText = utils . toEncodedString ( cipherText , "base64" , 'base64url' ) ;
67- const encodedAuthTag = utils . toEncodedString ( authTag , "base64" , 'base64url' ) ;
64+ const encodedEncryptedSecretKey = toEncodedString ( encryptedSecretKey , 'binary' , 'base64url' ) ;
65+ const encodedIv = toEncodedString ( iv , 'binary' , 'base64url' ) ;
66+ const encodedEncryptedText = toEncodedString ( cipherText , "base64" , 'base64url' ) ;
67+ const encodedAuthTag = toEncodedString ( authTag , "base64" , 'base64url' ) ;
6868
6969 const encryptedData = serialize ( encodedJweHeader , encodedEncryptedSecretKey , encodedIv , encodedEncryptedText , encodedAuthTag ) ;
7070 return { [ this . encryptedValueFieldName ] : encryptedData } ;
@@ -91,7 +91,7 @@ function JweCrypto(config) {
9191 let secretKey = nodeCrypto . privateDecrypt (
9292 {
9393 key : this . privateKey ,
94- padding : nodeCrypto . constants . RSA_NO_PADDING ,
94+ padding : nodeCrypto . constants . RSA_PKCS1_OAEP_PADDING ,
9595 oaepHash : "sha256"
9696 } ,
9797 Buffer . from ( encryptedSecretKey , 'binary' )
@@ -178,6 +178,9 @@ function computePublicFingerprint(config, encryptionCertificate) {
178178 * @private
179179 */
180180function isValidConfig ( config ) {
181+ if ( ! utils . nodeVersionSupportsJWE ( ) ) {
182+ throw Error ( "JWE Encryption is only supported on Node 13+" ) ;
183+ }
181184 const propertiesBasic = [ "encryptionCertificate" , "encryptedValueFieldName" ] ;
182185 const contains = ( props ) => {
183186 return props . every ( ( elem ) => {
@@ -230,4 +233,19 @@ function validateRootMapping(config) {
230233 } ) ;
231234}
232235
236+ /**
237+ * @private
238+ */
239+ function toEncodedString ( value , fromFormat , toFormat ) {
240+ let result = Buffer . from ( value , fromFormat ) ;
241+ if ( toFormat === 'base64url' ) {
242+ result = result . toString ( 'base64' ) ;
243+ result = result . replace ( ( / \+ / g) , "-" ) ;
244+ result = result . replace ( ( / \\ / g) , "_" ) ;
245+ return result . replace ( ( / = / g) , "" ) ;
246+ } else {
247+ return result . toString ( toFormat ) ;
248+ }
249+ }
250+
233251module . exports = JweCrypto ;
0 commit comments