首页 > 技术文章 > node 常用方法 生成密钥 token验证 验证码生成 (持续更新)

yz-blog 2021-01-22 16:35 原文

node 常用方法 生成密钥 token验证 验证码生成

生成密钥

//生成密钥
    generateToken(data, expires = 7200) {
        const exp = Math.floor(Date.now() / 1000) + expires
        const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_private_key.pem')) // 私钥,看后面生成方法
        const token = jwt.sign({data, exp}, cert, {algorithm: 'RS256'})
        return token
    }
#生成rsa_private_key.pem文件命令 ssh-keygen -t rsa -C "xxx@qq.com"

验证token的方法

// 验证token的方法
    verifyToken(token) {
        let cert = fs.readFileSync(path.join(__dirname, '../public/rsa_public_key.pem'));//公钥
        let res = ''
        try {
            let result = jwt.verify(token, cert, {algorithms: ['RS256']}) || {};
            let {exp} = result, current = Math.floor(Date.now() / 1000);
            if (current <= exp) {
                res = result.data || {};
            }
        } catch (e) {
            console.log(e);
        }
        return res;
    }

生成验证码

/**
     * 生成验证码
     * */
    captcha(){
        var captcha = svgCaptcha.create({
            size: 4,
            fontSize: 40,
            width: 111,
            height: 36,
            color:'red',
            bacground: '#cc9966'
        })
        const _uuid = uuid.v1();
        this.app.redis.set(_uuid, captcha.text.toLowerCase())
        return {
            code:200,
            uuid:_uuid,
            img: captcha.data,
            msg: "操作成功",
        }
    }

# 依赖svgCaptcha插件

  

推荐阅读