ZBLOG

js使用已有Ecc公钥且base64编码的密钥加密

在JavaScript中,可以使用 Web Crypto API 来加密数据,使用已有的 ECC 公钥和 Base64 编码的密钥。以下是一个示例,演示如何进行此操作:

示例代码

  1. 将 Base64 编码的公钥转换为 CryptoKey 对象
  2. 使用该公钥加密数据

下面是具体的步骤:

  1. async function importEccPublicKey(base64PublicKey) {
  2. // 将Base64编码的字符串转换为字节数组
  3. const binaryDerString = window.atob(base64PublicKey);
  4. const binaryDer = new Uint8Array(binaryDerString.length);
  5. for (let i = 0; i < binaryDerString.length; i++) {
  6. binaryDer[i] = binaryDerString.charCodeAt(i);
  7. }
  8. // 导入公钥
  9. return await crypto.subtle.importKey(
  10. "spki", // Key format: Subject Public Key Info (SPKI)
  11. binaryDer,
  12. { name: "ECDSA", namedCurve: "P-256" }, // 使用适合你密钥曲线(如 P-256)
  13. true, // 是否可以导出
  14. ["encrypt"] // 用于加密
  15. );
  16. }
  17. async function encryptData(publicKey, data) {
  18. const encodedData = new TextEncoder().encode(data);
  19. // 加密数据
  20. const ciphertext = await crypto.subtle.encrypt(
  21. {
  22. name: "ECDH", // 使用椭圆曲线 Diffie-Hellman 算法或根据需求选择算法
  23. public: publicKey
  24. },
  25. publicKey,
  26. encodedData
  27. );
  28. return ciphertext;
  29. }
  30. // 示例用法:
  31. (async () => {
  32. const base64PublicKey = "YOUR_BASE64_PUBLIC_KEY"; // 替换成你的Base64公钥字符串
  33. const dataToEncrypt = "Hello, World!";
  34. try {
  35. const publicKey = await importEccPublicKey(base64PublicKey);
  36. const encryptedData = await encryptData(publicKey, dataToEncrypt);
  37. console.log("Encrypted Data:", new Uint8Array(encryptedData));
  38. // 如果需要,你可以将encryptedData转为base64格式再输出:
  39. const encryptedBase64 = btoa(String.fromCharCode(...new Uint8Array(encryptedData)));
  40. console.log("Encrypted Data in Base64:", encryptedBase64);
  41. } catch (error) {
  42. console.error("Error:", error);
  43. }
  44. })();

注意事项

  1. 安全性:确保在安全环境中使用此代码,以避免敏感信息泄露。
  2. ECC 曲线:确保替换 namedCurve 为与您的公钥匹配的曲线,例如 P-256, P-384P-521
  3. 浏览器兼容性:Web Crypto API 在现代浏览器中受支持,但请检查其兼容性以确保在目标平台上可用。
  4. 错误处理:实际应用中,务必加入适当的错误处理逻辑。

以上代码仅作为参考,可能需根据具体情况做调整。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=20940

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?