前端加密的几种方式 以及如何实现
时间: 2024-03-02 20:50:29 浏览: 31
前端加密有以下几种方式:
1. 对称加密:使用相同的密钥进行加密和解密,常见的算法有DES、3DES、AES等。实现方式如下:
```javascript
// 加密
function encryptByAES(message, secretKey) {
const key = CryptoJS.enc.Utf8.parse(secretKey);
const encrypted = CryptoJS.AES.encrypt(message, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
// 解密
function decryptByAES(ciphertext, secretKey) {
const key = CryptoJS.enc.Utf8.parse(secretKey);
const decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
```
2. 非对称加密:使用公钥和私钥进行加密和解密,常见的算法有RSA、DSA等。实现方式如下:
```javascript
// 生成公钥和私钥
const keyPair = window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), // 65537
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
// 加密
async function encryptByRSA(message, publicKey) {
const encodedMessage = new TextEncoder().encode(message);
const encrypted = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
publicKey,
encodedMessage
);
return window.btoa(String.fromCharCode(...new Uint8Array(encrypted)));
}
// 解密
async function decryptByRSA(ciphertext, privateKey) {
const decodedCiphertext = Uint8Array.from(
atob(ciphertext),
c => c.charCodeAt(0)
);
const decrypted = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
privateKey,
decodedCiphertext
);
return new TextDecoder().decode(decrypted);
}
```
3. 散列加密:将数据转化为固定长度的散列值,常见的算法有MD5、SHA-1、SHA-256等。实现方式如下:
```javascript
// 计算MD5散列值
function hashByMD5(message) {
return CryptoJS.MD5(message).toString();
}
// 计算SHA-256散列值
function hashBySHA256(message) {
return CryptoJS.SHA256(message).toString();
}
```
4. 混淆加密:通过混淆代码或者加入噪音的方式来增强安全性,常见的方式有代码混淆、字符替换等。实现方式如下:
```javascript
// 字符串替换
function replaceChars(str) {
return str.replace(/a/g, "@").replace(/e/g, "3").replace(/i/g, "1");
}
// 代码混淆
function obfuscateCode(code) {
// 实现方式可以使用自己的加密算法,这里只是示例
return code.split("").reverse().join("");
}
```
需要注意的是,以上示例代码只是参考实现,实际情况需要根据具体需求进行修改和完善。