@@ -15,8 +15,10 @@ const {
1515 createPrivateKey,
1616 KeyObject,
1717 randomBytes,
18+ publicDecrypt,
1819 publicEncrypt,
19- privateDecrypt
20+ privateDecrypt,
21+ privateEncrypt
2022} = require ( 'crypto' ) ;
2123
2224const fixtures = require ( '../common/fixtures' ) ;
@@ -156,7 +158,16 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
156158 assert ( Buffer . isBuffer ( privateDER ) ) ;
157159
158160 const plaintext = Buffer . from ( 'Hello world' , 'utf8' ) ;
159- const ciphertexts = [
161+ const testDecryption = ( fn , ciphertexts , decryptionKeys ) => {
162+ for ( const ciphertext of ciphertexts ) {
163+ for ( const key of decryptionKeys ) {
164+ const deciphered = fn ( key , ciphertext ) ;
165+ assert . deepStrictEqual ( deciphered , plaintext ) ;
166+ }
167+ }
168+ } ;
169+
170+ testDecryption ( privateDecrypt , [
160171 // Encrypt using the public key.
161172 publicEncrypt ( publicKey , plaintext ) ,
162173 publicEncrypt ( { key : publicKey } , plaintext ) ,
@@ -173,20 +184,25 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
173184 // DER-encoded data only.
174185 publicEncrypt ( { format : 'der' , type : 'pkcs1' , key : publicDER } , plaintext ) ,
175186 publicEncrypt ( { format : 'der' , type : 'pkcs1' , key : privateDER } , plaintext )
176- ] ;
177-
178- const decryptionKeys = [
187+ ] , [
179188 privateKey ,
180189 { format : 'pem' , key : privatePem } ,
181190 { format : 'der' , type : 'pkcs1' , key : privateDER }
182- ] ;
191+ ] ) ;
183192
184- for ( const ciphertext of ciphertexts ) {
185- for ( const key of decryptionKeys ) {
186- const deciphered = privateDecrypt ( key , ciphertext ) ;
187- assert ( plaintext . equals ( deciphered ) ) ;
188- }
189- }
193+ testDecryption ( publicDecrypt , [
194+ privateEncrypt ( privateKey , plaintext )
195+ ] , [
196+ // Decrypt using the public key.
197+ publicKey ,
198+ { format : 'pem' , key : publicPem } ,
199+ { format : 'der' , type : 'pkcs1' , key : publicDER } ,
200+
201+ // Decrypt using the private key.
202+ privateKey ,
203+ { format : 'pem' , key : privatePem } ,
204+ { format : 'der' , type : 'pkcs1' , key : privateDER }
205+ ] ) ;
190206}
191207
192208{
0 commit comments