LoginSignup
4
3

More than 3 years have passed since last update.

BIP39ニーモニックから秘密鍵を生成する

Last updated at Posted at 2020-02-23

普通、BIP39のニーモニックはHDウォレットと組み合わせて使われ、実際に利用する秘密鍵は親秘密鍵から生成された下位の秘密鍵になる。
それはそれとして、HDウォレット系のライブラリを使わず親秘密鍵を生成する方法を調べてみた。

HDウォレットと組み合わせて使う場合は hdkey を使うか、
Ethereumで使うなら ethereumjs-wallet/hdkey を使うか、
truffleと使うなら @truffle/hdwallet-provider を使うとよさそう。

方法

BIP39のニーモニックを生成

ニーモニックからシードに変換

HMAC-SHA512に通す

左256ビットを取り出す

秘密鍵

コード

// BIP39 Mnemonic code for generating deterministic keys
// https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
const bip39 = require('bip39');
const mnemonic = bip39.generateMnemonic();
const seed = bip39.mnemonicToSeedSync(mnemonic);

// BIP32 Hierarchical Deterministic Wallets
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
const crypto = require('crypto');
const key = Buffer.from('Bitcoin seed', 'utf8');
const hmac = crypto.createHmac('sha512', key)

const hash = hmac.update(seed).digest();
const privateKey = hash.slice(0, 32);

console.log(privateKey.toString('hex'))

注意点

ここで使ったニーモニックをHDウォレット用に再利用しないほうがいい。
マスターキーを直接使ってしまった状態なので。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3