数字签名是一种保证数据完整性和认证来源的技术。在JavaScript中,可以使用Web Crypto API来进行数字签名。
首先,需要创建一个CryptoKey对象,该对象包含用于数字签名的密钥。密钥可以是公钥或私钥,具体取决于您是要对数据进行签名还是验证签名。
// 生成密钥对
window.crypto.subtle.generateKey(
{
name: "RSA-PSS", // 签名算法
modulusLength: 2048, // 密钥长度
publicExponent: new Uint8Array([1, 0, 1]), // 公钥指数
hash: {name: "SHA-256"} // 哈希算法
},
true, // 是否可导出私钥
["sign", "verify"] // 密钥用途
).then(function(keyPair) {
// 获取私钥
window.crypto.subtle.exportKey(
"jwk", // 密钥格式
keyPair.privateKey // 私钥
).then(function(privateKey) {
console.log(privateKey);
});
});
上述代码生成了一个RSA-PSS密钥对,密钥长度为2048位,公钥指数为65537,哈希算法为SHA-256。密钥用途为签名和验证。
然后,可以使用生成的密钥对对数据进行数字签名。
const data = "Hello, world!";
const encodedData = new TextEncoder().encode(data);
window.crypto.subtle.sign(
{
name: "RSA-PSS",
saltLength: 32 // 盐的长度
},
keyPair.privateKey, // 私钥
encodedData // 要签名的数据
).then(function(signature) {
console.log(new Uint8Array(signature));
});
上述代码使用RSA-PSS算法对Hello, world!进行数字签名。
加密是一种保护数据机密性的技术。在JavaScript中,可以使用Web Crypto API来进行加密。
首先,需要创建一个CryptoKey对象,该对象包含用于加密和解密的密钥。密钥可以是公钥或私钥,具体取决于您是要对数据进行加密还是解密。
// 生成密钥对
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP", // 加密算法
modulusLength: 2048, // 密钥长度
publicExponent: new Uint8Array([1, 0, 1]), // 公钥指数
hash: {name: "SHA-256"} // 哈希算法
},
true, // 是否可导出私钥
["encrypt", "decrypt"] // 密钥用途
).then(function(keyPair) {
// 获取公钥
window.crypto.subtle.exportKey(
"jwk", // 密钥格式
keyPair.publicKey // 公钥
).then(function(publicKey) {
console.log(publicKey);
});
});
上述代码生成了一个RSA-OAEP密钥对,密钥长度为2048位,公钥指数为65537,哈希算法为SHA-256。密钥用途为加密和解密。
然后,可以使用生成的公钥对数据进行加密。
const data = "Hello, world!";
const encodedData = new TextEncoder().encode(data);
window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
keyPair.publicKey, // 公钥
encodedData // 要加密的数据
).then(function(ciphertext) {
console.log(new Uint8Array(ciphertext));
});
上述代码使用RSA-OAEP算法对Hello, world!进行加密。