Base64编码:
优点:
缺点:
示例代码:
// 编码
const encodedData = btoa('Hello, World!');
console.log(encodedData);
// 解码
const decodedData = atob(encodedData);
console.log(decodedData);
哈希函数:
优点:
缺点:
示例代码: 使用JavaScript的crypto.subtle
来计算SHA-256哈希值的示例代码:
async function calculateSHA256Hash(data) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
return hashHex;
}
const originalData = 'Hello, World!';
calculateSHA256Hash(originalData).then(hash => {
console.log(hash); // SHA-256哈希值
});
对称加密:
优点:
缺点:
示例代码: 使用Web Crypto API进行AES加密的示例代码:
async function encryptData(data, key) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const encryptedData = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: new Uint8Array(12) }, key, dataBuffer);
return new Uint8Array(encryptedData);
}
async function decryptData(encryptedData, key) {
const decryptedData = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(12) }, key, encryptedData);
const decoder = new TextDecoder();
return decoder.decode(decryptedData);
}
// 生成随机AES密钥
crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']).then(key => {
const originalData = 'Hello, World!';
encryptData(originalData, key)
.then(encryptedData => decryptData(encryptedData, key))
.then(decryptedData => {
console.log(decryptedData); // 解密后的数据
});
});
非对称加密:
优点:
缺点:
示例代码: 使用Node.js中的crypto
模块执行RSA加密的示例代码:
const crypto = require('crypto');
// 生成RSA密钥对
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
});
const originalData = 'Hello, World!';
// 加密
const encryptedData = crypto.publicEncrypt(publicKey, Buffer.from(originalData));
console.log(encryptedData.toString('base64'));
// 解密
const decryptedData = crypto.privateDecrypt(privateKey, encryptedData);
console.log(decryptedData.toString());
js在线加密是一款国内顶尖的js保护方案,已经有许多客户使用。同时配备了一键在线解密其他简单加密的功能.