• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23// Flags: --expose-internals
24
25// This is the same as test/simple/test-crypto, but from before the shift
26// to use buffers by default.
27
28
29const common = require('../common');
30
31if (!common.hasCrypto)
32  common.skip('missing crypto');
33
34const assert = require('assert');
35const crypto = require('crypto');
36const fs = require('fs');
37const tls = require('tls');
38const fixtures = require('../common/fixtures');
39
40require('internal/crypto/util').setDefaultEncoding('latin1');
41
42// Test Certificates
43const certPem = fixtures.readKey('rsa_cert.crt');
44const certPfx = fixtures.readKey('rsa_cert.pfx');
45const keyPem = fixtures.readKey('rsa_private.pem');
46const rsaPubPem = fixtures.readKey('rsa_public.pem', 'ascii');
47const rsaKeyPem = fixtures.readKey('rsa_private.pem', 'ascii');
48
49// PFX tests
50tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' });
51
52assert.throws(function() {
53  tls.createSecureContext({ pfx: certPfx });
54}, /^Error: mac verify failure$/);
55
56assert.throws(function() {
57  tls.createSecureContext({ pfx: certPfx, passphrase: 'test' });
58}, /^Error: mac verify failure$/);
59
60assert.throws(function() {
61  tls.createSecureContext({ pfx: 'sample', passphrase: 'test' });
62}, /^Error: not enough data$/);
63
64// Test HMAC
65{
66  const hmacHash = crypto.createHmac('sha1', 'Node')
67                         .update('some data')
68                         .update('to hmac')
69                         .digest('hex');
70  assert.strictEqual(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892');
71}
72
73// Test HMAC-SHA-* (rfc 4231 Test Cases)
74{
75  const rfc4231 = [
76    {
77      key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
78      data: Buffer.from('4869205468657265', 'hex'), // 'Hi There'
79      hmac: {
80        sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22',
81        sha256:
82            'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' +
83            '2e32cff7',
84        sha384:
85            'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' +
86            '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6',
87        sha512:
88            '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' +
89            '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' +
90            '2e696c203a126854'
91      }
92    },
93    {
94      key: Buffer.from('4a656665', 'hex'), // 'Jefe'
95      data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' +
96                        '96e673f', 'hex'), // 'what do ya want for nothing?'
97      hmac: {
98        sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44',
99        sha256:
100            '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' +
101            '64ec3843',
102        sha384:
103            'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' +
104            '6322445e8e2240ca5e69e2c78b3239ecfab21649',
105        sha512:
106            '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' +
107            'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' +
108            '636e070a38bce737'
109      }
110    },
111    {
112      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
113      data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
114                        'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
115                        'hex'),
116      hmac: {
117        sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea',
118        sha256:
119            '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' +
120            'ced565fe',
121        sha384:
122            '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' +
123            '5966144b2a5ab39dc13814b94e3ab6e101a34f27',
124        sha512:
125            'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' +
126            'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' +
127            '74278859e13292fb'
128      }
129    },
130    {
131      key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
132                       'hex'),
133      data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
134                        'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
135                        'hex'),
136      hmac: {
137        sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a',
138        sha256:
139            '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' +
140            '6729665b',
141        sha384:
142            '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' +
143            '1f573b4e6801dd23c4a7d679ccf8a386c674cffb',
144        sha512:
145            'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' +
146            '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' +
147            'e2adebeb10a298dd'
148      }
149    },
150    {
151      key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
152      // 'Test With Truncation'
153      data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'),
154      hmac: {
155        sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8',
156        sha256: 'a3b6167473100ee06e0c796c2955552b',
157        sha384: '3abf34c3503b2a23a46efc619baef897',
158        sha512: '415fad6271580a531d4179bc891d87a6'
159      },
160      truncate: true
161    },
162    {
163      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
164                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
165                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
166                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
167                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
168                       'aaaaaaaaaaaa', 'hex'),
169      // 'Test Using Larger Than Block-Size Key - Hash Key First'
170      data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' +
171                        'c6f636b2d53697a65204b6579202d2048617368204b657920' +
172                        '4669727374', 'hex'),
173      hmac: {
174        sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e',
175        sha256:
176            '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' +
177            '0ee37f54',
178        sha384:
179            '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' +
180            '033ac4c60c2ef6ab4030fe8296248df163f44952',
181        sha512:
182            '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' +
183            '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' +
184            '8b915a985d786598'
185      }
186    },
187    {
188      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
189                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
190                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
191                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
192                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
193                       'aaaaaaaaaaaa', 'hex'),
194      // 'This is a test using a larger than block-size key and a larger ' +
195      // 'than block-size data. The key needs to be hashed before being ' +
196      // 'used by the HMAC algorithm.'
197      data: Buffer.from('5468697320697320612074657374207573696e672061206c6' +
198                        '172676572207468616e20626c6f636b2d73697a65206b6579' +
199                        '20616e642061206c6172676572207468616e20626c6f636b2' +
200                        'd73697a6520646174612e20546865206b6579206e65656473' +
201                        '20746f20626520686173686564206265666f7265206265696' +
202                        'e6720757365642062792074686520484d414320616c676f72' +
203                        '6974686d2e', 'hex'),
204      hmac: {
205        sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1',
206        sha256:
207            '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' +
208            '5c3a35e2',
209        sha384:
210            '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' +
211            '461e99c5a678cc31e799176d3860e6110c46523e',
212        sha512:
213            'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' +
214            '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' +
215            '65c97440fa8c6a58'
216      }
217    },
218  ];
219
220  for (const testCase of rfc4231) {
221    for (const hash in testCase.hmac) {
222      let result = crypto.createHmac(hash, testCase.key)
223                       .update(testCase.data)
224                       .digest('hex');
225      if (testCase.truncate) {
226        result = result.substr(0, 32); // first 128 bits == 32 hex chars
227      }
228      assert.strictEqual(
229        testCase.hmac[hash],
230        result
231      );
232    }
233  }
234}
235
236// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases)
237{
238  const rfc2202_md5 = [
239    {
240      key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
241      data: 'Hi There',
242      hmac: '9294727a3638bb1c13f48ef8158bfc9d'
243    },
244    {
245      key: 'Jefe',
246      data: 'what do ya want for nothing?',
247      hmac: '750c783e6ab0b503eaa86e310a5db738'
248    },
249    {
250      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
251      data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
252                        'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
253                        'hex'),
254      hmac: '56be34521d144c88dbb8c733f0e8b3f6'
255    },
256    {
257      key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
258                       'hex'),
259      data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
260                        'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
261                        'cdcdcdcdcd',
262                        'hex'),
263      hmac: '697eaf0aca3a3aea3a75164746ffaa79'
264    },
265    {
266      key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
267      data: 'Test With Truncation',
268      hmac: '56461ef2342edc00f9bab995690efd4c'
269    },
270    {
271      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
272                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
273                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
274                       'aaaaaaaaaaaaaaaaaaaaaa',
275                       'hex'),
276      data: 'Test Using Larger Than Block-Size Key - Hash Key First',
277      hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd'
278    },
279    {
280      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
281                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
282                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
283                       'aaaaaaaaaaaaaaaaaaaaaa',
284                       'hex'),
285      data:
286          'Test Using Larger Than Block-Size Key and Larger Than One ' +
287          'Block-Size Data',
288      hmac: '6f630fad67cda0ee1fb1f562db3aa53e'
289    },
290  ];
291  const rfc2202_sha1 = [
292    {
293      key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
294      data: 'Hi There',
295      hmac: 'b617318655057264e28bc0b6fb378c8ef146be00'
296    },
297    {
298      key: 'Jefe',
299      data: 'what do ya want for nothing?',
300      hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'
301    },
302    {
303      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
304      data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' +
305                        'ddddddddddddddddddddddddddddddddddddddddddddd' +
306                        'dddddddddd',
307                        'hex'),
308      hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3'
309    },
310    {
311      key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
312                       'hex'),
313      data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
314                        'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
315                        'cdcdcdcdcd',
316                        'hex'),
317      hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da'
318    },
319    {
320      key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
321      data: 'Test With Truncation',
322      hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04'
323    },
324    {
325      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
326                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
327                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
328                       'aaaaaaaaaaaaaaaaaaaaaa',
329                       'hex'),
330      data: 'Test Using Larger Than Block-Size Key - Hash Key First',
331      hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112'
332    },
333    {
334      key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
335                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
336                       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
337                       'aaaaaaaaaaaaaaaaaaaaaa',
338                       'hex'),
339      data:
340          'Test Using Larger Than Block-Size Key and Larger Than One ' +
341          'Block-Size Data',
342      hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91'
343    },
344  ];
345
346  if (!common.hasFipsCrypto) {
347    for (const testCase of rfc2202_md5) {
348      assert.strictEqual(
349        testCase.hmac,
350        crypto.createHmac('md5', testCase.key)
351          .update(testCase.data)
352          .digest('hex')
353      );
354    }
355  }
356  for (const testCase of rfc2202_sha1) {
357    assert.strictEqual(
358      testCase.hmac,
359      crypto.createHmac('sha1', testCase.key)
360        .update(testCase.data)
361        .digest('hex')
362    );
363  }
364}
365
366// Test hashing
367{
368  const a1 = crypto.createHash('sha1').update('Test123').digest('hex');
369  const a2 = crypto.createHash('sha256').update('Test123').digest('base64');
370  const a3 = crypto.createHash('sha512').update('Test123').digest(); // binary
371  const a4 = crypto.createHash('sha1').update('Test123').digest('buffer');
372
373  if (!common.hasFipsCrypto) {
374    const a0 = crypto.createHash('md5').update('Test123').digest('latin1');
375    assert.strictEqual(
376      a0,
377      'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c'
378    );
379  }
380
381  assert.strictEqual(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2');
382
383  assert.strictEqual(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=');
384
385  // Test SHA512 as assumed latin1
386  assert.strictEqual(
387    a3,
388    '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
389    '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' +
390    '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' +
391    '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' +
392    '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\''
393  );
394
395  assert.deepStrictEqual(
396    a4,
397    Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex')
398  );
399}
400
401// Test multiple updates to same hash
402{
403  const h1 = crypto.createHash('sha1').update('Test123').digest('hex');
404  const h2 = crypto.createHash('sha1').update('Test').update('123')
405    .digest('hex');
406  assert.strictEqual(h1, h2);
407}
408
409// Test hashing for binary files
410{
411  const fn = fixtures.path('sample.png');
412  const sha1Hash = crypto.createHash('sha1');
413  const fileStream = fs.createReadStream(fn);
414  fileStream.on('data', function(data) {
415    sha1Hash.update(data);
416  });
417  fileStream.on('close', common.mustCall(function() {
418    assert.strictEqual(
419      sha1Hash.digest('hex'),
420      '22723e553129a336ad96e10f6aecdf0f45e4149e'
421    );
422  }));
423}
424
425// Unknown digest method should throw an error:
426// https://github.com/nodejs/node-v0.x-archive/issues/2227
427assert.throws(function() {
428  crypto.createHash('xyzzy');
429}, /^Error: Digest method not supported$/);
430
431// Test signing and verifying
432{
433  const s1 = crypto.createSign('SHA1')
434                 .update('Test123')
435                 .sign(keyPem, 'base64');
436  const s1Verified = crypto.createVerify('SHA1')
437                         .update('Test')
438                         .update('123')
439                         .verify(certPem, s1, 'base64');
440  assert.strictEqual(s1Verified, true);
441
442  const s2 = crypto.createSign('SHA256')
443                 .update('Test123')
444                 .sign(keyPem); // binary
445  const s2Verified = crypto.createVerify('SHA256')
446                         .update('Test')
447                         .update('123')
448                         .verify(certPem, s2); // binary
449  assert.strictEqual(s2Verified, true);
450
451  const s3 = crypto.createSign('SHA1')
452                 .update('Test123')
453                 .sign(keyPem, 'buffer');
454  const s3Verified = crypto.createVerify('SHA1')
455                         .update('Test')
456                         .update('123')
457                         .verify(certPem, s3);
458  assert.strictEqual(s3Verified, true);
459}
460
461
462function testCipher1(key) {
463  // Test encryption and decryption
464  const plaintext = 'Keep this a secret? No! Tell everyone about node.js!';
465  const cipher = crypto.createCipher('aes192', key);
466
467  // Encrypt plaintext which is in utf8 format
468  // to a ciphertext which will be in hex
469  let ciph = cipher.update(plaintext, 'utf8', 'hex');
470  // Only use binary or hex, not base64.
471  ciph += cipher.final('hex');
472
473  const decipher = crypto.createDecipher('aes192', key);
474  let txt = decipher.update(ciph, 'hex', 'utf8');
475  txt += decipher.final('utf8');
476
477  assert.strictEqual(txt, plaintext);
478}
479
480
481function testCipher2(key) {
482  // Encryption and decryption with Base64.
483  // Reported in https://github.com/joyent/node/issues/738
484  const plaintext =
485      '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
486      'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
487      'jAfaFg**';
488  const cipher = crypto.createCipher('aes256', key);
489
490  // Encrypt plaintext which is in utf8 format
491  // to a ciphertext which will be in Base64
492  let ciph = cipher.update(plaintext, 'utf8', 'base64');
493  ciph += cipher.final('base64');
494
495  const decipher = crypto.createDecipher('aes256', key);
496  let txt = decipher.update(ciph, 'base64', 'utf8');
497  txt += decipher.final('utf8');
498
499  assert.strictEqual(txt, plaintext);
500}
501
502
503function testCipher3(key, iv) {
504  // Test encryption and decryption with explicit key and iv
505  const plaintext =
506      '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
507      'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
508      'jAfaFg**';
509  const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv);
510  let ciph = cipher.update(plaintext, 'utf8', 'hex');
511  ciph += cipher.final('hex');
512
513  const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv);
514  let txt = decipher.update(ciph, 'hex', 'utf8');
515  txt += decipher.final('utf8');
516
517  assert.strictEqual(txt, plaintext);
518}
519
520
521function testCipher4(key, iv) {
522  // Test encryption and decryption with explicit key and iv
523  const plaintext =
524      '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
525      'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
526      'jAfaFg**';
527  const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv);
528  let ciph = cipher.update(plaintext, 'utf8', 'buffer');
529  ciph = Buffer.concat([ciph, cipher.final('buffer')]);
530
531  const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv);
532  let txt = decipher.update(ciph, 'buffer', 'utf8');
533  txt += decipher.final('utf8');
534
535  assert.strictEqual(txt, plaintext);
536}
537
538
539function testCipher5(key, iv) {
540  // Test encryption and decryption with explicit key with aes128-wrap
541  const plaintext =
542      '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
543      'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
544      'jAfaFg**';
545  const cipher = crypto.createCipher('id-aes128-wrap', key);
546  let ciph = cipher.update(plaintext, 'utf8', 'buffer');
547  ciph = Buffer.concat([ciph, cipher.final('buffer')]);
548
549  const decipher = crypto.createDecipher('id-aes128-wrap', key);
550  let txt = decipher.update(ciph, 'buffer', 'utf8');
551  txt += decipher.final('utf8');
552
553  assert.strictEqual(txt, plaintext);
554}
555
556if (!common.hasFipsCrypto) {
557  testCipher1('MySecretKey123');
558  testCipher1(Buffer.from('MySecretKey123'));
559
560  testCipher2('0123456789abcdef');
561  testCipher2(Buffer.from('0123456789abcdef'));
562
563  testCipher5(Buffer.from('0123456789abcd0123456789'));
564}
565
566testCipher3('0123456789abcd0123456789', '12345678');
567testCipher3('0123456789abcd0123456789', Buffer.from('12345678'));
568testCipher3(Buffer.from('0123456789abcd0123456789'), '12345678');
569testCipher3(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
570
571testCipher4(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
572
573
574// update() should only take buffers / strings
575assert.throws(
576  () => crypto.createHash('sha1').update({ foo: 'bar' }),
577  {
578    code: 'ERR_INVALID_ARG_TYPE',
579    name: 'TypeError'
580  });
581
582
583// Test Diffie-Hellman with two parties sharing a secret,
584// using various encodings as we go along
585{
586  const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256);
587  const p1 = dh1.getPrime('buffer');
588  const dh2 = crypto.createDiffieHellman(p1, 'base64');
589  const key1 = dh1.generateKeys();
590  const key2 = dh2.generateKeys('hex');
591  const secret1 = dh1.computeSecret(key2, 'hex', 'base64');
592  const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer');
593
594  assert.strictEqual(secret1, secret2.toString('base64'));
595
596  // Create "another dh1" using generated keys from dh1,
597  // and compute secret again
598  const dh3 = crypto.createDiffieHellman(p1, 'buffer');
599  const privkey1 = dh1.getPrivateKey();
600  dh3.setPublicKey(key1);
601  dh3.setPrivateKey(privkey1);
602
603  assert.strictEqual(dh1.getPrime(), dh3.getPrime());
604  assert.strictEqual(dh1.getGenerator(), dh3.getGenerator());
605  assert.strictEqual(dh1.getPublicKey(), dh3.getPublicKey());
606  assert.strictEqual(dh1.getPrivateKey(), dh3.getPrivateKey());
607
608  const secret3 = dh3.computeSecret(key2, 'hex', 'base64');
609
610  assert.strictEqual(secret1, secret3);
611
612  // https://github.com/joyent/node/issues/2338
613  const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
614            '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' +
615            '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +
616            'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
617  crypto.createDiffieHellman(p, 'hex');
618
619  // Test RSA key signing/verification
620  const rsaSign = crypto.createSign('SHA1');
621  const rsaVerify = crypto.createVerify('SHA1');
622  assert.ok(rsaSign instanceof crypto.Sign);
623  assert.ok(rsaVerify instanceof crypto.Verify);
624
625  rsaSign.update(rsaPubPem);
626  const rsaSignature = rsaSign.sign(rsaKeyPem, 'hex');
627  const expectedSignature = fixtures.readKey(
628    'rsa_public_sha1_signature_signedby_rsa_private.sha1',
629    'hex'
630  );
631  assert.strictEqual(rsaSignature, expectedSignature);
632
633  rsaVerify.update(rsaPubPem);
634  assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true);
635}
636
637//
638// Test RSA signing and verification
639//
640{
641  const privateKey = fixtures.readKey('rsa_private_b.pem');
642  const publicKey = fixtures.readKey('rsa_public_b.pem');
643
644  const input = 'I AM THE WALRUS';
645
646  const signature = fixtures.readKey(
647    'I_AM_THE_WALRUS_sha256_signature_signedby_rsa_private_b.sha256',
648    'hex'
649  );
650
651  const sign = crypto.createSign('SHA256');
652  sign.update(input);
653
654  const output = sign.sign(privateKey, 'hex');
655  assert.strictEqual(output, signature);
656
657  const verify = crypto.createVerify('SHA256');
658  verify.update(input);
659
660  assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true);
661}
662
663
664//
665// Test DSA signing and verification
666//
667{
668  const privateKey = fixtures.readKey('dsa_private.pem');
669  const publicKey = fixtures.readKey('dsa_public.pem');
670
671  const input = 'I AM THE WALRUS';
672
673  // DSA signatures vary across runs so there is no static string to verify
674  // against
675  const sign = crypto.createSign('SHA1');
676  sign.update(input);
677  const signature = sign.sign(privateKey, 'hex');
678
679  const verify = crypto.createVerify('SHA1');
680  verify.update(input);
681
682  assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true);
683}
684
685
686//
687// Test PBKDF2 with RFC 6070 test vectors (except #4)
688//
689function testPBKDF2(password, salt, iterations, keylen, expected) {
690  const actual = crypto.pbkdf2Sync(password, salt, iterations, keylen,
691                                   'sha256');
692  assert.strictEqual(actual, expected);
693
694  const cb = common.mustCall((err, actual) => {
695    assert.strictEqual(actual, expected);
696  });
697  crypto.pbkdf2(password, salt, iterations, keylen, 'sha256', cb);
698}
699
700
701testPBKDF2('password', 'salt', 1, 20,
702           '\x12\x0f\xb6\xcf\xfc\xf8\xb3\x2c\x43\xe7\x22\x52' +
703           '\x56\xc4\xf8\x37\xa8\x65\x48\xc9');
704
705testPBKDF2('password', 'salt', 2, 20,
706           '\xae\x4d\x0c\x95\xaf\x6b\x46\xd3\x2d\x0a\xdf\xf9' +
707           '\x28\xf0\x6d\xd0\x2a\x30\x3f\x8e');
708
709testPBKDF2('password', 'salt', 4096, 20,
710           '\xc5\xe4\x78\xd5\x92\x88\xc8\x41\xaa\x53\x0d\xb6' +
711           '\x84\x5c\x4c\x8d\x96\x28\x93\xa0');
712
713testPBKDF2('passwordPASSWORDpassword',
714           'saltSALTsaltSALTsaltSALTsaltSALTsalt',
715           4096,
716           25,
717           '\x34\x8c\x89\xdb\xcb\xd3\x2b\x2f\x32\xd8\x14\xb8' +
718           '\x11\x6e\x84\xcf\x2b\x17\x34\x7e\xbc\x18\x00\x18\x1c');
719
720testPBKDF2('pass\0word', 'sa\0lt', 4096, 16,
721           '\x89\xb6\x9d\x05\x16\xf8\x29\x89\x3c\x69\x62\x26' +
722           '\x65\x0a\x86\x87');
723