1 | const test = require('tape');
|
2 | const Cryptr = require('../');
|
3 |
|
4 | const testSecret = 'myTotalySecretKey';
|
5 | const testData = 'bacon';
|
6 |
|
7 | test('works...', t => {
|
8 | t.plan(1);
|
9 |
|
10 | const cryptr = new Cryptr(testSecret);
|
11 | const encryptedString = cryptr.encrypt(testData);
|
12 | const decryptedString = cryptr.decrypt(encryptedString);
|
13 |
|
14 | t.equal(decryptedString, testData, 'decrypted aes256 correctly');
|
15 | });
|
16 |
|
17 | test('works with utf8 specific characters', t => {
|
18 | t.plan(1);
|
19 |
|
20 | const testString = 'ßáÇÖÑ 🥓';
|
21 | const cryptr = new Cryptr(testSecret);
|
22 | const encryptedString = cryptr.encrypt(testString);
|
23 | const decryptedString = cryptr.decrypt(encryptedString);
|
24 |
|
25 | t.equal(decryptedString, testString, 'decrypted aes256 correctly with UTF8 chars');
|
26 | });
|
27 |
|
28 | test('goes bang if bad secret', t => {
|
29 | const badSecrets = [null, undefined, 0, 123451345134, '', Buffer.from('buffer'), {}];
|
30 |
|
31 | t.plan(badSecrets.length);
|
32 |
|
33 | for (let i = 0; i < badSecrets.length; i++) {
|
34 | t.throws(
|
35 | () => new Cryptr(badSecrets[i]),
|
36 | /Cryptr: secret must be a non-0-length string/,
|
37 | `throws on bad secret ${badSecrets[i]}`,
|
38 | );
|
39 | }
|
40 | });
|
41 |
|
42 | test('encrypt goes bang if value is null or undefined', t => {
|
43 | const cryptr = new Cryptr(testSecret);
|
44 | const badValues = [null, undefined];
|
45 |
|
46 | t.plan(badValues.length);
|
47 |
|
48 | for (let i = 0; i < badValues.length; i++) {
|
49 | t.throws(
|
50 | () => cryptr.encrypt(badValues[i]),
|
51 | /value must not be null or undefined/,
|
52 | `throws on value ${badValues[i]}`,
|
53 | );
|
54 | }
|
55 | });
|
56 |
|
57 | test('decrypt goes bang if value is null or undefined', t => {
|
58 | const cryptr = new Cryptr(testSecret);
|
59 | const badValues = [null, undefined];
|
60 |
|
61 | t.plan(badValues.length);
|
62 |
|
63 | for (let i = 0; i < badValues.length; i++) {
|
64 | t.throws(
|
65 | () => cryptr.decrypt(badValues[i]),
|
66 | /value must not be null or undefined/,
|
67 | `throws on value ${badValues[i]}`,
|
68 | );
|
69 | }
|
70 | });
|
71 |
|
72 | test('decrypt goes bang if value has been tampered with', t => {
|
73 | t.plan(1);
|
74 |
|
75 | const cryptr = new Cryptr(testSecret);
|
76 |
|
77 | const encryptedString = cryptr.encrypt(testData);
|
78 |
|
79 | const encryptedBuffer = Buffer.from(encryptedString, 'hex');
|
80 | const b1 = Buffer.from(testData);
|
81 | const b2 = Buffer.from('hello');
|
82 |
|
83 | for (let i = 0; i < b1.length; i++) {
|
84 | encryptedBuffer[i + 16] ^= b1[i] ^ b2[i];
|
85 | }
|
86 |
|
87 | const modifiedValue = encryptedBuffer.toString('hex');
|
88 |
|
89 | t.throws(
|
90 | () => cryptr.decrypt(modifiedValue),
|
91 | /Unsupported state or unable to authenticate data/,
|
92 | 'throws on tampered data',
|
93 | );
|
94 | });
|