UNPKG

2.29 kBJavaScriptView Raw
1const test = require('tape');
2const Cryptr = require('../');
3
4const testSecret = 'myTotalySecretKey';
5const testData = 'bacon';
6
7test('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
17test('goes bang if bad secret', t => {
18 const badSecrets = [null, undefined, 0, 123451345134, '', Buffer.from('buffer'), {}];
19
20 t.plan(badSecrets.length);
21
22 for (let i = 0; i < badSecrets.length; i++) {
23 t.throws(
24 () => new Cryptr(badSecrets[i]),
25 /Cryptr: secret must be a non-0-length string/,
26 `throws on bad secret ${badSecrets[i]}`,
27 );
28 }
29});
30
31test('encrypt goes bang if value is null or undefined', t => {
32 const cryptr = new Cryptr(testSecret);
33 const badValues = [null, undefined];
34
35 t.plan(badValues.length);
36
37 for (let i = 0; i < badValues.length; i++) {
38 t.throws(
39 () => cryptr.encrypt(badValues[i]),
40 /value must not be null or undefined/,
41 `throws on value ${badValues[i]}`,
42 );
43 }
44});
45
46test('decrypt goes bang if value is null or undefined', t => {
47 const cryptr = new Cryptr(testSecret);
48 const badValues = [null, undefined];
49
50 t.plan(badValues.length);
51
52 for (let i = 0; i < badValues.length; i++) {
53 t.throws(
54 () => cryptr.decrypt(badValues[i]),
55 /value must not be null or undefined/,
56 `throws on value ${badValues[i]}`,
57 );
58 }
59});
60
61test('decrypt goes bang if value has been tampered with', t => {
62 t.plan(1);
63
64 const cryptr = new Cryptr(testSecret);
65
66 const encryptedString = cryptr.encrypt(testData);
67
68 const encryptedBuffer = Buffer.from(encryptedString, 'hex');
69 const b1 = Buffer.from(testData);
70 const b2 = Buffer.from('hello');
71
72 for (let i = 0; i < b1.length; i++) {
73 encryptedBuffer[i + 16] ^= b1[i] ^ b2[i];
74 }
75
76 const modifiedValue = encryptedBuffer.toString('hex');
77
78 t.throws(
79 () => cryptr.decrypt(modifiedValue),
80 /Unsupported state or unable to authenticate data/,
81 'throws on tampered data',
82 );
83});