Nodejs CryptoJS 简单实现MD5 + HEX(aes-256-cbc) 加解密

学习 · 2022-05-06

简介

JavaScript implementations of standard and secure cryptographic algorithms
CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

标准和安全加密算法的 JavaScript 实现
CryptoJS 是使用最佳实践和模式在 JavaScript 中实现的标准和安全加密算法的不断增长的集合。 它们速度很快,并且具有一致且简单的界面。

文档

CryptoJS Gitbook

实现代码


import crypto from 'crypto';
import config from '~/config';

// Defining key
const key = crypto.randomBytes(32);
// Defining iv
const iv = crypto.randomBytes(16)

export function md5(str: string, upperCase = false): string {
    const hash = crypto.createHash('md5');

    hash.update(str, 'utf8');

    const ret = hash.digest('hex');

    return upperCase ? ret.toUpperCase() : ret;
}

export function encrypt(str: string): string {
    const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(config.crypto.key || key), Buffer.from(config.crypto.iv || iv));
    let crypted = cipher.update(str, 'utf8', 'hex');

    crypted += cipher.final('hex');

    return crypted;
}

export function decrypt(str: string): string {
    let result = null;

    try {
        const cipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(config.crypto.key || key), Buffer.from(config.crypto.iv || iv));
        const decrypted = cipher.update(str, 'hex', 'utf8');
        result = decrypted + cipher.final('utf8');
    } catch (e) {
        return result;
    }

    return result;
}
Nodejs CryptoJS MD5
Theme Jasmine by Kent Liao | 桂ICP备15008025号-6