比特币地址生成全步骤(golang实现)

  1. 通过椭圆曲线算法生成公钥
  2. 对公钥进行sha256散列和ripemd160散列,获得publickeyHash
  3. 在publickeyHash前面加上version(版本)字节数组获得versionPublickeyHash
  4. 对versionPublickeyHash进行两次sha256散列并取前4位字节,获得tailfHash
  5. 将tailfHash拼接到versionPublickeyHash后面,获得公钥的最终Hash即finalHash
  6. 最后将finalHash进行Base58编码(一种可视化工具)得到比特币地址

曾经有个疑问,为何比特币生成地址要这么麻烦,既然非对称加密只拥有公钥是无法倒推出私钥的,为何不直接使用公钥当地址,而是对公钥进行hash多次来取得地址,直到最近看了篇文章才明白,该文章提到量子计算机是可以破解椭圆曲线加密的,他可以通过公钥快速寻找到私钥信息。但是量子计算机很难逆转Hash算法(或者说需要2的80次方个步骤来破解Hash),所以你的比特币放在一个未支付过的地址中(根据UTXO交易模型,输出存的是公钥Hash而不是公钥,这同样解释了为何UTXO输入存的是公钥而输出存的是公钥Hash)是相当安全的。也就是说已有花费的地址在面对量子计算机面前是不安全的,没有花费的地址有较强的抗量子性。

在这里插入图片描述

代码实现:

package main

import (
    "bytes"
    "math/big"
)

var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")

func Base58Encode(input []byte) []byte {
    var result []byte

    x := big.NewInt(0).SetBytes(input)

    base := big.NewInt(int64(len(b58Alphabet)))
    zero := big.NewInt(0)
    mod := &big.Int{}

    for x.Cmp(zero) != 0 {
        x.DivMod(x, base, mod)
        result = append(result, b58Alphabet[mod.Int64()])
    }

    ReverseBytes(result)

    for _, b := range input {
        if b == 0x00 {
            result = append([]byte{b58Alphabet[0]}, result...)
        } else {
            break
        }
    }
    return result

}

func Base58Decode(input []byte) []byte {
    result := big.NewInt(0)
    zeroBytes := 0
    for _, b := range input {
        if b != b58Alphabet[0] {
            break
        }
        zeroBytes++
    }
    payload := input[zeroBytes:]
    for _, b := range payload {
        charIndex := bytes.IndexByte(b58Alphabet, b)
        result.Mul(result, big.NewInt(int64(len(b58Alphabet))))
        result.Add(result, big.NewInt(int64(charIndex)))
    }

    decoded := result.Bytes()
    decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)

    return decoded
}

func ReverseBytes(data []byte) {
    for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
        data[i], data[j] = data[j], data[i]
    }
}
package main

import (
    "bytes"
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/sha256"
    "fmt"
    "golang.org/x/crypto/ripemd160"
    "log"
)

const VERSION = byte(0x00)
const CHECKSUM_LENGTH = 4

type BitcoinKeys struct {
    PrivateKey *ecdsa.PrivateKey
    PublicKey  []byte
}

func GetBitcoinKeys() *BitcoinKeys {
    b := &BitcoinKeys{nil, nil}
    b.newKeyPair()
    return b
}

func (b *BitcoinKeys) newKeyPair() {
    curve := elliptic.P256()
    var err error
    b.PrivateKey, err = ecdsa.GenerateKey(curve, rand.Reader)
    if err != nil {
        log.Panic(err)
    }
    b.PublicKey = append(b.PrivateKey.PublicKey.X.Bytes(), b.PrivateKey.PublicKey.Y.Bytes()...)
}

//获取地址
func (b *BitcoinKeys) GetAddress() []byte {
    //1.ripemd160(sha256(publickey))
    ripPubKey := GeneratePublicKeyHash(b.PublicKey)
    //2.最前面添加一个字节的版本信息获得 versionPublickeyHash
    versionPublickeyHash := append([]byte{VERSION}, ripPubKey[:]...)
    //3.sha256(sha256(versionPublickeyHash))  取最后四个字节的值
    tailHash := CheckSumHash(versionPublickeyHash)
    //4.拼接最终hash versionPublickeyHash + checksumHash
    finalHash := append(versionPublickeyHash, tailHash...)
    //进行base58加密
    address := Base58Encode(finalHash)
    return address
}

func GeneratePublicKeyHash(publicKey []byte) []byte {
    sha256PubKey := sha256.Sum256(publicKey)
    r := ripemd160.New()
    r.Write(sha256PubKey[:])
    ripPubKey := r.Sum(nil)
    return ripPubKey
}

//通过地址获得公钥
func GetPublicKeyHashFromAddress(address string) []byte {
    addressBytes := []byte(address)
    fullHash := Base58Decode(addressBytes)
    publicKeyHash := fullHash[1 : len(fullHash)-CHECKSUM_LENGTH]
    return publicKeyHash
}

func CheckSumHash(versionPublickeyHash []byte) []byte {
    versionPublickeyHashSha1 := sha256.Sum256(versionPublickeyHash)
    versionPublickeyHashSha2 := sha256.Sum256(versionPublickeyHashSha1[:])
    tailHash := versionPublickeyHashSha2[:CHECKSUM_LENGTH]
    return tailHash
}

//检测比特币地址是否有效
func IsVaildBitcoinAddress(address string) bool {
    adddressByte := []byte(address)
    fullHash := Base58Decode(adddressByte)
    if len(fullHash) != 25 {
        return false
    }
    prefixHash := fullHash[:len(fullHash)-CHECKSUM_LENGTH]
    tailHash := fullHash[len(fullHash)-CHECKSUM_LENGTH:]
    tailHash2 := CheckSumHash(prefixHash)
    if bytes.Compare(tailHash, tailHash2[:]) == 0 {
        return true
    } else {
        return false
    }
}

func main() {
    keys := GetBitcoinKeys()
    bitcoinAddress := keys.GetAddress()
    fmt.Println("比特币地址:", string(bitcoinAddress))
    fmt.Printf("比特币地址是否有效:%v\n:", IsVaildBitcoinAddress(string(bitcoinAddress)))
}

运行结果:

比特币地址: 1BeDkWNHxvVc8DmpLVpFRPUngPmG7uCRHJ
比特币地址是否有效:true

你可能感兴趣的:(比特币地址生成全步骤(golang实现))