Add Diffie-Hellman support to crypto module
[platform/upstream/nodejs.git] / test / simple / test-crypto.js
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 var common = require('../common');
23 var assert = require('assert');
24
25 try {
26   var crypto = require('crypto');
27 } catch (e) {
28   console.log('Not compiled with OPENSSL support.');
29   process.exit();
30 }
31
32 var fs = require('fs');
33 var path = require('path');
34
35 // Test Certificates
36 var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii');
37 var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii');
38 var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii');
39
40 try {
41   var credentials = crypto.createCredentials(
42                                              {key: keyPem,
43                                                cert: certPem,
44                                                ca: caPem});
45 } catch (e) {
46   console.log('Not compiled with OPENSSL support.');
47   process.exit();
48 }
49
50 // Test HMAC
51
52 var h1 = crypto.createHmac('sha1', 'Node')
53                .update('some data')
54                .update('to hmac')
55                .digest('hex');
56 assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC');
57
58 // Test hashing
59 var a0 = crypto.createHash('sha1').update('Test123').digest('hex');
60 var a1 = crypto.createHash('md5').update('Test123').digest('binary');
61 var a2 = crypto.createHash('sha256').update('Test123').digest('base64');
62 var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary
63
64 assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1');
65 assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' +
66              '\u00bd\u008c', 'Test MD5 as binary');
67 assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=',
68              'Test SHA256 as base64');
69 assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
70                  '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' +
71                  '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' +
72                  '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' +
73                  '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'',
74              'Test SHA512 as assumed binary');
75
76 // Test multiple updates to same hash
77 var h1 = crypto.createHash('sha1').update('Test123').digest('hex');
78 var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex');
79 assert.equal(h1, h2, 'multipled updates');
80
81 // Test hashing for binary files
82 var fn = path.join(common.fixturesDir, 'sample.png');
83 var sha1Hash = crypto.createHash('sha1');
84 var fileStream = fs.createReadStream(fn);
85 fileStream.addListener('data', function(data) {
86   sha1Hash.update(data);
87 });
88 fileStream.addListener('close', function() {
89   assert.equal(sha1Hash.digest('hex'),
90                '22723e553129a336ad96e10f6aecdf0f45e4149e',
91                'Test SHA1 of sample.png');
92 });
93
94 // Test signing and verifying
95 var s1 = crypto.createSign('RSA-SHA1')
96                .update('Test123')
97                .sign(keyPem, 'base64');
98 var verified = crypto.createVerify('RSA-SHA1')
99                      .update('Test')
100                      .update('123')
101                      .verify(certPem, s1, 'base64');
102 assert.ok(verified, 'sign and verify (base 64)');
103
104 var s2 = crypto.createSign('RSA-SHA256')
105                .update('Test123')
106                .sign(keyPem); // binary
107 var verified = crypto.createVerify('RSA-SHA256')
108                      .update('Test')
109                      .update('123')
110                      .verify(certPem, s2); // binary
111 assert.ok(verified, 'sign and verify (binary)');
112
113 // Test encryption and decryption
114 var plaintext = 'Keep this a secret? No! Tell everyone about node.js!';
115 var cipher = crypto.createCipher('aes192', 'MySecretKey123');
116
117 // encrypt plaintext which is in utf8 format
118 // to a ciphertext which will be in hex
119 var ciph = cipher.update(plaintext, 'utf8', 'hex');
120 // Only use binary or hex, not base64.
121 ciph += cipher.final('hex');
122
123 var decipher = crypto.createDecipher('aes192', 'MySecretKey123');
124 var txt = decipher.update(ciph, 'hex', 'utf8');
125 txt += decipher.final('utf8');
126
127 assert.equal(txt, plaintext, 'encryption and decryption');
128
129 // Test encyrption and decryption with explicit key and iv
130 var encryption_key = '0123456789abcd0123456789';
131 var iv = '12345678';
132
133 var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
134 var ciph = cipher.update(plaintext, 'utf8', 'hex');
135 ciph += cipher.final('hex');
136
137 var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
138 var txt = decipher.update(ciph, 'hex', 'utf8');
139 txt += decipher.final('utf8');
140
141 assert.equal(txt, plaintext, 'encryption and decryption with key and iv');
142
143 // update() should only take buffers / strings
144 assert.throws(function() {
145   crypto.createHash('sha1').update({foo: 'bar'});
146 }, /string or buffer/);
147
148 // Test Diffie-Hellman with two parties sharing a secret,
149 // using various encodings as we go along
150 var dh1 = crypto.createDiffieHellman(256);
151 var p1 = dh1.getPrime('base64');
152 var dh2 = crypto.createDiffieHellman(p1, 'base64');
153 var key1 = dh1.generateKeys();
154 var key2 = dh2.generateKeys('hex');
155 var secret1 = dh1.computeSecret(key2, 'hex', 'base64');
156 var secret2 = dh2.computeSecret(key1, 'binary', 'base64');
157
158 assert.equal(secret1, secret2);
159
160 // Create "another dh1" using generated keys from dh1,
161 // and compute secret again
162 var dh3 = crypto.createDiffieHellman(p1, 'base64');
163 var privkey1 = dh1.getPrivateKey();
164 dh3.setPublicKey(key1);
165 dh3.setPrivateKey(privkey1);
166
167 assert.equal(dh1.getPrime(), dh3.getPrime());
168 assert.equal(dh1.getGenerator(), dh3.getGenerator());
169 assert.equal(dh1.getPublicKey(), dh3.getPublicKey());
170 assert.equal(dh1.getPrivateKey(), dh3.getPrivateKey());
171
172 var secret3 = dh3.computeSecret(key2, 'hex', 'base64');
173
174 assert.equal(secret1, secret3);