onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190531 - Nodejs 加密解密 #35

Open onvno opened 5 years ago

onvno commented 5 years ago

生成随机码

crypto.randomBytes(size, [callback]) 生成加密用的伪随机码,支持2种方法,当传递cb的话就是异步方法,不传cb就是同步方法:

// 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
}

使用

// 加密不解密
function pureEncrypt(str, secret) {
  const md5 = crypto.createHash('md5');
  const enc = md5.update(str + secret)
  const encCode = enc.digest('hex');

  return encCode
}

const enc = pureEncrypt("myusername@", crypto.randomBytes(10).toString)