在JavaScript中,字符串加密和解密通常涉及到使用特定的加密算法来转换原始字符串为不可读的密文,以及将密文还原为原始字符串的过程。以下是一些基础概念、优势、类型、应用场景以及示例代码:
常见的加密类型包括对称加密和非对称加密。
以下是一个使用JavaScript的Crypto API进行AES对称加密和解密的示例:
// 加密函数
async function encrypt(text, key) {
const encoder = new TextEncoder();
const encodedText = encoder.encode(text);
const cryptoKey = await crypto.subtle.importKey(
"raw",
encoder.encode(key),
{ name: "AES-GCM" },
false,
["encrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
cryptoKey,
encodedText
);
return {
iv: Array.from(iv),
encrypted: Array.from(new Uint8Array(encrypted)),
};
}
// 解密函数
async function decrypt(encryptedData, key) {
const decoder = new TextDecoder();
const cryptoKey = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(key),
{ name: "AES-GCM" },
false,
["decrypt"]
);
const decrypted = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: new Uint8Array(encryptedData.iv),
},
cryptoKey,
new Uint8Array(encryptedData.encrypted)
);
return decoder.decode(decrypted);
}
// 使用示例
(async () => {
const secretKey = "my-secret-key";
const originalText = "Hello, World!";
const encryptedData = await encrypt(originalText, secretKey);
console.log("Encrypted:", encryptedData);
const decryptedText = await decrypt(encryptedData, secretKey);
console.log("Decrypted:", decryptedText);
})();
如果你遇到了具体的加密解密问题,可以提供更详细的信息,以便进一步分析和解决。
领取专属 10元无门槛券
手把手带您无忧上云