Last active
June 1, 2020 22:09
-
-
Save qzaidi/5401800 to your computer and use it in GitHub Desktop.
Emulates Java's insecure PBEWITHMD5ANDDES with node.js crypto. Useful for interop with old java programs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
/* | |
* Emulates Java's PBEWITHMD5ANDDES for node.js | |
*/ | |
var crypto = require('crypto'); | |
var pbewithmd5anddes = { | |
KDF: function(password,salt,iterations) { | |
var pwd = new Buffer(password,'utf-8'); | |
var key = Buffer.concat([pwd, salt]); | |
var i; | |
for (i = 0; i < iterations; i+=1) { | |
key = crypto.createHash("md5").update(key).digest(); | |
} | |
return key; | |
}, | |
getKeyIV: function(password,salt,iterations) { | |
var key = this.KDF(password,salt,iterations); | |
var keybuf = new Buffer(key,'binary').slice(0,8); | |
var ivbuf = new Buffer(key,'binary').slice(8,16); | |
return [ keybuf, ivbuf ]; | |
}, | |
encrypt: function(payload,password,salt,iterations,cb) { | |
var kiv = this.getKeyIV(password,salt,iterations); | |
var cipher = crypto.createCipheriv('des', kiv[0],kiv[1]); | |
var encrypted = []; | |
encrypted.push(cipher.update(payload,'utf-8','hex')); | |
encrypted.push(cipher.final('hex')); | |
return cb(undefined,new Buffer(encrypted.join(''),'hex').toString('base64')); | |
}, | |
decrypt: function(payload,password,salt,iterations,cb) { | |
var encryptedBuffer = new Buffer(payload,'base64'); | |
var kiv = this.getKeyIV(password,salt,iterations); | |
var decipher = crypto.createDecipheriv('des', kiv[0],kiv[1]); | |
var decrypted = []; | |
decrypted.push(decipher.update(encryptedBuffer)); | |
decrypted.push(decipher.final()); | |
return cb(undefined, decrypted.join('')); | |
} | |
}; | |
module.exports = pbewithmd5anddes; | |
/* ---------------- TEST CODE ---------------- */ | |
(function() { | |
if (require.main === module) { | |
var password = 'test'; | |
var iterations = 19; | |
var salt = new Buffer('d99bce325735e303','hex'); | |
pbewithmd5anddes.encrypt('helloworld',password,salt,iterations,function(err,msg) { | |
console.log('encrypted: ' + msg); | |
// eat your own dogfood | |
pbewithmd5anddes.decrypt(msg,password,salt,iterations,function(err,msg) { | |
console.log('decrypted: ' + msg); | |
}); | |
}); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!