Javascript如何高效存储ECIES方案的Secp256k1私钥

问题描述

我一直很难弄清楚如何从多个库中存储一个 Secp256k1 私钥(目前在这个用于 ECIES 加密的库:https://npm.io/package/@toruslabs/eccrypto)。

我尝试过使用 base64 编码和解码,许多函数的实现将输入编码字符串的数组缓冲区复制到 localStorage 和对应的输出 Uint8Array 从 localStorage,我尝试使用 IndexedDB,JSON.stringify 和 parse 不适用于二进制数据,以及更多变体。

当我单独遍历数组缓冲区元素以将其复制到新的 Uint8Array 中时,我得到了一个类似的私钥,但是缺少两个键/字段(父项和偏移量),我相信这就是我尝试过的每个库的原因当我尝试从它们生成公钥时,far 会返回很长的“坏私钥”行。

我已经筋疲力尽了,由于我在这个特定主题上缺乏技能,我想获得一些专业见解。那么我如何存储(以任何方式,只要它是客户端/本地)Secp256k1 私钥,如果我从那个持久的客户端数据库调用它,它们可以用来生成公钥?

解决方法

显然,使用私钥/公钥(在本例中为 @toruslabs/eccrypto)的库需要密钥的缓冲区参数。

一个简单的解决方案是通过 browserify 使 NodeJS Buffer 在浏览器中可用。在创建 browserify 文件时,您只需要将 NodeJS Buffer 类包含到 window 对象中,如下所示:

const eccrypto = require('./index');
window.eccrypto = eccrypto;
window.Buffer = Buffer;

然后,使用 browserify 生成包文件:browserify main.js -o bundle.js

此后,您将能够在浏览器中使用 Buffer 类,这将使加载私钥/公钥成为可能。示例代码在这里:

<script src="bundle.js"></script>
<script>
  const eccrypto = window.eccrypto;

  const privateKey = eccrypto.generatePrivate();
  const publicKey = eccrypto.getPublic(privateKey);

  // hex string output of private key
  const hexPrivateKey = privateKey.toString('hex')
  console.log(hexPrivateKey); // we can do this as privateKey is a Buffer

  // load private key again
  const newPrivateKey = Buffer.from(hexPrivateKey,'hex');
 
  const enc = new TextEncoder();

  // code referenced from @toruslabs/eccrypto README
  // Encrypting the message.
  eccrypto.encrypt(publicKey,enc.encode("my testing msg")).then(function (encrypted) {
    // Decrypting the message.
    eccrypto.decrypt(newPrivateKey,encrypted).then(function (plaintext) {
      console.log("Message:",plaintext.toString());
    });
  });
</script>

这应该足以将私钥的十六进制字符串存储在 localStorage 或您将使用的任何客户端数据库/存储中。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...