簡體   English   中英

Javascript。 ECIES方案如何有效存儲Secp256k1私鑰

[英]Javascript. How To Efficiently Store Secp256k1 Private Key for ECIES Scheme

我一直很難弄清楚如何從多個庫中存儲一個 Secp256k1 privateKey(目前在這個庫上用於 ECIES 加密: https://npm.io/package/@toruslabs/eccrypto )。

I have tried encoding and decoding with base64, many implementations of functions that copy array buffer for input encoded string to localStoarge and corresponding output Uint8Array from localStorage, I tried it with IndexedDB, JSON.stringify and parse do not work with binary data, and so更多的變化。

當我通過數組緩沖區元素 go 分別將其復制到新的 Uint8Array 中時,我得到了一個類似的私鑰,但是缺少兩個鍵/字段(父級和偏移量),我相信這就是為什么我到目前為止嘗試過的每個庫都會返回一些東西當我嘗試從它們生成公鑰時,會出現很長的“壞私鑰”行。

我已經筋疲力盡了,我想要一些專業的見解,因為我在這個特定的主題上缺乏技能。 那么如何存儲(只要它是客戶端/本地的)Secp256k1 私鑰,如果我從該持久客戶端數據庫調用它,它們可以用於生成公鑰?

顯然,使用私鑰/公鑰的庫(在本例中為@toruslabs/eccrypto )需要密鑰的緩沖區參數。

一個簡單的解決方案是通過 browserify 使NodeJS 緩沖區在瀏覽器中可用。 創建 browserify 文件時,您只需要將 NodeJS 緩沖區 class 包含到 window object 中,如下所示:

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

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

在此之后,您將能夠在瀏覽器中使用緩沖區 class,這將使加載私鑰/公鑰成為可能。 示例代碼在這里:

<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 或您將使用的任何客戶端數據庫/存儲中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM