Secure random token in Node.js

后端 未结 12 1024
盖世英雄少女心
盖世英雄少女心 2020-11-28 00:05

In this question Erik needs to generate a secure random token in Node.js. There\'s the method crypto.randomBytes that generates a random Buffer. However, the ba

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 00:52

    Look at real_ates ES2016 way, it's more correct.

    ECMAScript 2016 (ES7) way

    import crypto from 'crypto';
    
    function spawnTokenBuf() {
        return function(callback) {
            crypto.randomBytes(48, callback);
        };
    }
    
    async function() {
        console.log((await spawnTokenBuf()).toString('base64'));
    };
    

    Generator/Yield Way

    var crypto = require('crypto');
    var co = require('co');
    
    function spawnTokenBuf() {
        return function(callback) {
            crypto.randomBytes(48, callback);
        };
    }
    
    co(function* () {
        console.log((yield spawnTokenBuf()).toString('base64'));
    });
    

提交回复
热议问题