保存以下代码到 lotuskey/key.go
package lotuskey
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
)
const (
SECP256K1 = iota
BLS
)
// lotus 私钥格式
type KeyInfo struct {
Type string
PrivateKey string
}
func (k *KeyInfo) Format() string {
bz, _ := json.Marshal(k)
return hex.EncodeToString(bz)
}
// 私钥转为lotus格式
func ConvertToLotusKey(privateKey string, format int) (string, error) {
keyType := ""
switch format {
case SECP256K1:
keyType = "secp256k1"
case BLS:
keyType = "bls"
default:
return "", fmt.Errorf("invalid format")
}
bz, err := hex.DecodeString(privateKey)
if err != nil {
return "", err
}
privateKey = base64.StdEncoding.EncodeToString(bz)
k := KeyInfo{
Type: keyType,
PrivateKey: privateKey,
}
return k.Format(), nil
}
// 解析lotus key
func ParseLotusKeyInfo(key string) (string, error) {
var k KeyInfo
bz, err := hex.DecodeString(key)
if err != nil {
return "", err
}
err = json.Unmarshal(bz, &k)
if err != nil {
return "", err
}
bz, err = base64.StdEncoding.DecodeString(k.PrivateKey)
if err != nil {
return "", err
}
return hex.EncodeToString(bz), nil
}
使用方法:
1 解析导出的私钥:ParseLotusKeyInfo
// 通过lotus wallet export导出的私钥
s := "7b2254797065223a22736563703235366b31222c22507269766174654b6579223a226861482b783259726a456b325259686f57306c456d6d73577a6970544538476676736b6c677576646f36493d227d"
k, err := lotuskey.ParseLotusKeyInfo(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(k)
2 普通私钥转为lotus私钥格式 ConvertToLotusKey
// 私钥
k = "8b8f0adade019d6471e0cfbdc191db73cae1836d4c9fd3a99deb8c3707626815"
// secp256k1格式
k, err := lotuskey.ConvertToLotusKey(k, lotuskey.SECP256K1)
// bls格式
// k, err := lotuskey.ConvertToLotusKey(k, lotuskey.BLS)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(k)