RSA和AES加密JavaScript示例 - 使用CryptoJS和jsrsasign库
这是一个简单的RSA和AES加密的demo,使用了CryptoJS和jsrsasign库。
RSA加密:
// 生成RSA密钥对
const keyPair = KEYUTIL.generateKeypair('RSA', 1024);
// 获取公钥
const publicKey = KEYUTIL.getPEM(keyPair.pubKeyObj);
// 加密数据
const encryptedData = CryptoJS.enc.Utf8.parse('hello world');
const encrypted = keyPair.encrypt(encryptedData);
console.log('RSA公钥:', publicKey);
console.log('RSA加密后的数据:', encrypted);
AES加密:
// 设置AES密钥和偏移量
const key = CryptoJS.enc.Hex.parse('0123456789abcdef0123456789abcdef');
const iv = CryptoJS.enc.Hex.parse('abcdef9876543210abcdef9876543210');
// 加密数据
const plainText = 'hello world';
const encrypted = CryptoJS.AES.encrypt(plainText, key, { iv: iv });
console.log('AES加密后的数据:', encrypted.toString());
完整的代码如下:
// 加载jsrsasign库
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/10.3.0/jsrsasign-all-min.js"></script>
// RSA加密
// 生成RSA密钥对
const keyPair = KEYUTIL.generateKeypair('RSA', 1024);
// 获取公钥
const publicKey = KEYUTIL.getPEM(keyPair.pubKeyObj);
// 加密数据
const encryptedData = CryptoJS.enc.Utf8.parse('hello world');
const encrypted = keyPair.encrypt(encryptedData);
console.log('RSA公钥:', publicKey);
console.log('RSA加密后的数据:', encrypted);
// AES加密
// 设置AES密钥和偏移量
const key = CryptoJS.enc.Hex.parse('0123456789abcdef0123456789abcdef');
const iv = CryptoJS.enc.Hex.parse('abcdef9876543210abcdef9876543210');
// 加密数据
const plainText = 'hello world';
const encrypted = CryptoJS.AES.encrypt(plainText, key, { iv: iv });
console.log('AES加密后的数据:', encrypted.toString());
原文地址: https://www.cveoy.top/t/topic/l3YU 著作权归作者所有。请勿转载和采集!