助記詞(Mnemonics)生成種子,以及Public Key, Private key 原

HD錢包其實就是管理一堆的Seed以及密鑰。記住32byte的私鑰是個反人性的事。所以,就有了助記詞(Mnemonics)。本文討論由助記詞(Mnemonics)生成種子, and vice versa. 

 

首先,借用Mastering Bitcoin書裏的幾張圖,說明一下HD錢包

 

下面是變換框圖

圖片借用到此爲止,下面是捋代碼

如何生成初始的熵(entropy)

func NewEntropy(bitSize int) ([]byte, error) {
	err := validateEntropyBitSize(bitSize)
	if err != nil {
		return nil, err
	}

	entropy := make([]byte, bitSize/8)
	_, err = rand.Read(entropy)
	return entropy, err
}

validateEntropyBitsize : bitSize只能是128,256,512。一定是8的倍數

 

如何生成checksum

func addChecksum(data []byte) []byte {
	// Get first byte of sha256
	hasher := sha256.New()
	hasher.Write(data)
	hash := hasher.Sum(nil)
	firstChecksumByte := hash[0]

	// len() is in bytes so we divide by 4
	checksumBitLength := uint(len(data) / 4)

	// For each bit of check sum we want we shift the data one the left
	// and then set the (new) right most bit equal to checksum bit at that index
	// staring from the left
	dataBigInt := new(big.Int).SetBytes(data)
	for i := uint(0); i < checksumBitLength; i++ {
		// Bitshift 1 left
		dataBigInt.Mul(dataBigInt, bigTwo)

		// Set rightmost bit if leftmost checksum bit is set
		if uint8(firstChecksumByte&(1<<(7-i))) > 0 {
			dataBigInt.Or(dataBigInt, bigOne)
		}
	}

	return dataBigInt.Bytes()
}

剩下把bits分成12個segment,然後查字典,就不用說了吧

 

字典在此

測試向量在此

此處驗證

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章