在JavaScript中,对URL中的参数进行加密和解密通常是为了保护敏感信息,防止数据在传输过程中被截获或篡改。以下是一些基础概念、优势、类型、应用场景以及如何实现加密和解密的方法。
?
后面的部分,由键值对组成,例如https://example.com/page?param1=value1¶m2=value2
。以下是一个使用JavaScript的Crypto API进行AES加密和解密的示例:
// 加密函数
function encrypt(text, secretKey) {
const encoder = new TextEncoder();
const encodedText = encoder.encode(text);
const cryptoKey = await crypto.subtle.importKey(
'raw',
encoder.encode(secretKey),
{ name: 'AES-GCM' },
false,
['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const encryptedData = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
cryptoKey,
encodedText
);
return {
iv: Array.from(iv),
data: Array.from(new Uint8Array(encryptedData))
};
}
// 解密函数
async function decrypt(encryptedData, secretKey) {
const decoder = new TextDecoder();
const cryptoKey = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secretKey),
{ name: 'AES-GCM' },
false,
['decrypt']
);
const decryptedData = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: new Uint8Array(encryptedData.iv) },
cryptoKey,
new Uint8Array(encryptedData.data)
);
return decoder.decode(decryptedData);
}
// 使用示例
(async () => {
const secretKey = 'my-secret-key'; // 应该是一个安全的随机字符串
const paramValue = 'sensitive-data';
const encrypted = await encrypt(paramValue, secretKey);
console.log('Encrypted:', encrypted);
const decrypted = await decrypt(encrypted, secretKey);
console.log('Decrypted:', decrypted);
})();
在实际应用中,你可能需要将加密后的数据编码为URL安全的格式,例如Base64,以便在URL中传输。
如果在加密或解密过程中遇到问题,可以检查以下几点:
如果问题依然存在,可以提供具体的错误信息或行为描述,以便进一步诊断问题。
领取专属 10元无门槛券
手把手带您无忧上云