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



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

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

当我单独遍历数组缓冲区元素以将其复制到一个新的Uint8Array中时,我会得到一个类似的私钥,但缺少两个键/字段(父和偏移(,我相信这就是为什么我迄今为止尝试的每个库都会返回一个很长的"行;坏私钥";当我尝试从它们生成公钥时。

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

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

一个简单的解决方案是通过browserfy在浏览器中提供NodeJS缓冲区。在创建browserfy文件时,您只需要将NodeJS Buffer类包含到窗口对象中,如图所示:

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

然后,使用browserfy: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或您将要使用的任何客户端数据库/存储中。

最新更新