Node(十二)加密解密

token:(引入jsonwebtoken模塊)


對稱加密,一個祕鑰進行加密解密

const crypto = require('crypto');

// 產生token

let obj = {

    a: 1,

    b: 2,

};

let sec = 'HelloWorld'

let res = jwt.sign(obj, sec,{ algorithm: 'RS256'});//傳入加密的對象,祕鑰,加密方式

console.log(res);

//解析token

let sec2 = jwt.verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJpYXQiOjE1NDM5ODA0NTF9.ORMQa_LBbDCd7XEEHgVGN2EnccL2kTOyDidE-b4ANMY', sec);

console.log(sec2);

非對稱加密,經過私鑰進行加密,公鑰解密

產生私鑰 openssl genrsa -out private_key.pem 1024javascript

由私鑰產生公鑰 openssl rsa -in private_key.pem -pubout -out public_key.pemjava

var selfkey = fs.readFileSync(path.join(__dirname, 'key.pem'));//讀取私鑰路徑
var jwtset = jwt.sign({
    a: 1,
    b: 2,
    c: 3
}, selfkey, {
    algorithm: 'RS256'
});
console.log(jwtset);

var otherkey = fs.readFileSync(path.join(__dirname, 'public_key.pem'));//讀取公鑰路徑
var jwtget = jwt.verify(jwtset, otherkey, {
    algorithm: 'RS256'
});
console.log(jwtget);

 crypto和bcrypt

// 數據庫密碼加密
// 內置crypto
// MD5
const hash = crypto.createHash('md5');
hash.update('HelloWorld');
console.log(hash.digest('hex'));
// Hmac
const hmac = crypto.createHmac('sha256', '12345');
hmac.update('HelloWorld');
console.log(hmac.digest('hex'));
// 第三方bcrypt
const pass = 'qazwsx123';
const saltRounds = 10;
bcrypt.genSalt(saltRounds, (err, salt) => {
    bcrypt.hash(pass, salt, (err, hash) => {
        let result= bcrypt.compareSync('qazwsx123', hash);
        console.log(result);
    });
});
相關文章
相關標籤/搜索