node.js-v0.8API解读(5)- Crypto(补完)
by snoopyxdy
at 2012-09-03 00:04:50
original http://snoopyxdy.blog.163.com/blog/static/6011744020128211113692
var crypto = require('crypto');var alice = crypto.getDiffieHellman('modp5');var bob = crypto.getDiffieHellman('modp5');alice.generateKeys();bob.generateKeys();var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');/* alice_secret and bob_secret should be the same */console.log(alice_secret == bob_secret);
var crypto = require("crypto");
var assert = require("assert");
var diffieHellman1 = crypto.createDiffieHellman(256);
var prime1 = diffieHellman1.getPrime('base64');
var diffieHellman2 = crypto.createDiffieHellman(prime1, 'base64');
var key1 = diffieHellman1.generateKeys();
var key2 = diffieHellman2.generateKeys('hex');
var secret1 = diffieHellman1.computeSecret(key2, 'hex', 'base64');
var secret2 = diffieHellman2.computeSecret(key1, 'binary', 'base64');
assert.equal(secret1, secret2);
// async
crypto.randomBytes(256, function(ex, buf) {
if (ex) throw ex;
console.log('Have %d bytes of random data: %s', buf.length, buf);
});
// sync
try {
var buf = crypto.randomBytes(256);
console.log('Have %d bytes of random data: %s', buf.length, buf);
} catch (ex) {
// handle error
}
crypto.randomBytes(128, function (err, salt) {
if (err) { throw err;}
salt = new Buffer(salt).toString('hex');
crypto.pbkdf2('123456', salt, 7000, 256, function (err,hash) {
if (err) { throw err; }
hash = new Buffer(hash).toString('hex');
console.log(hash);
})
})