File tree Expand file tree Collapse file tree 2 files changed +31
-3
lines changed
Expand file tree Collapse file tree 2 files changed +31
-3
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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
1727test ( 'goes bang if bad secret' , t => {
You can’t perform that action at this time.
0 commit comments