Skip to content

Commit b703720

Browse files
committed
fix breaking change in 4.0.1 branch (still support smaller iv sizes)
1 parent a4ca933 commit b703720

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

index.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,27 @@ function Cryptr(secret) {
3232
const stringValue = String(value);
3333
const iv = Buffer.from(stringValue.slice(0, 32), 'hex');
3434
const encrypted = stringValue.slice(32);
35+
let legacyValue = false;
36+
let decipher;
37+
38+
try {
39+
decipher = crypto.createDecipheriv(algorithm, key, iv);
40+
} catch (exception) {
41+
if (exception.message === 'Invalid IV length') {
42+
legacyValue = true;
43+
} else {
44+
throw exception;
45+
}
46+
}
47+
48+
if (!legacyValue) {
49+
return decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8');
50+
}
3551

36-
const decipher = crypto.createDecipheriv(algorithm, key, iv);
37-
return decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8');
52+
const legacyIv = stringValue.slice(0, 16);
53+
const legacyEncrypted = stringValue.slice(16);
54+
decipher = crypto.createDecipheriv(algorithm, key, legacyIv);
55+
return decipher.update(legacyEncrypted, 'hex', 'utf8') + decipher.final('utf8');
3856
};
3957
}
4058

tests/index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,17 @@ test('works...', t => {
1111
const encryptedString = cryptr.encrypt(testData);
1212
const decryptedString = cryptr.decrypt(encryptedString);
1313

14-
t.equal(decryptedString, testData, 'decrypted aes256 correctly');
14+
t.equal(decryptedString, testData, 'decrypted sha256 correctly');
15+
});
16+
17+
test('works with old iv size values', t => {
18+
t.plan(1);
19+
20+
const cryptr = new Cryptr(testSecret);
21+
22+
const decryptedString = cryptr.decrypt('5590fd6409be2494de0226f5d7');
23+
24+
t.equal(decryptedString, 'bacon', 'decrypted old iv value');
1525
});
1626

1727
test('goes bang if bad secret', t => {

0 commit comments

Comments
 (0)