@@ -15,8 +15,10 @@ const {
15
15
createPrivateKey,
16
16
KeyObject,
17
17
randomBytes,
18
+ publicDecrypt,
18
19
publicEncrypt,
19
- privateDecrypt
20
+ privateDecrypt,
21
+ privateEncrypt
20
22
} = require ( 'crypto' ) ;
21
23
22
24
const fixtures = require ( '../common/fixtures' ) ;
@@ -156,7 +158,16 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
156
158
assert ( Buffer . isBuffer ( privateDER ) ) ;
157
159
158
160
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 , [
160
171
// Encrypt using the public key.
161
172
publicEncrypt ( publicKey , plaintext ) ,
162
173
publicEncrypt ( { key : publicKey } , plaintext ) ,
@@ -173,20 +184,25 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
173
184
// DER-encoded data only.
174
185
publicEncrypt ( { format : 'der' , type : 'pkcs1' , key : publicDER } , plaintext ) ,
175
186
publicEncrypt ( { format : 'der' , type : 'pkcs1' , key : privateDER } , plaintext )
176
- ] ;
177
-
178
- const decryptionKeys = [
187
+ ] , [
179
188
privateKey ,
180
189
{ format : 'pem' , key : privatePem } ,
181
190
{ format : 'der' , type : 'pkcs1' , key : privateDER }
182
- ] ;
191
+ ] ) ;
183
192
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
+ ] ) ;
190
206
}
191
207
192
208
{
0 commit comments