github.com/jonasnick/go-ethereum@v0.7.12-0.20150216215225-22176f05d387/crypto/keypair.go (about)

     1  package crypto
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/jonasnick/go-ethereum/crypto/secp256k1"
     7  	"github.com/jonasnick/go-ethereum/ethutil"
     8  )
     9  
    10  type KeyPair struct {
    11  	PrivateKey []byte
    12  	PublicKey  []byte
    13  	address    []byte
    14  	mnemonic   string
    15  	// The associated account
    16  	// account *StateObject
    17  }
    18  
    19  func GenerateNewKeyPair() *KeyPair {
    20  	_, prv := secp256k1.GenerateKeyPair()
    21  	keyPair, _ := NewKeyPairFromSec(prv) // swallow error, this one cannot err
    22  	return keyPair
    23  }
    24  
    25  func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) {
    26  	pubkey, err := secp256k1.GeneratePubKey(seckey)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	return &KeyPair{PrivateKey: seckey, PublicKey: pubkey}, nil
    32  }
    33  
    34  func (k *KeyPair) Address() []byte {
    35  	if k.address == nil {
    36  		k.address = Sha3(k.PublicKey[1:])[12:]
    37  	}
    38  	return k.address
    39  }
    40  
    41  func (k *KeyPair) Mnemonic() string {
    42  	if k.mnemonic == "" {
    43  		k.mnemonic = strings.Join(MnemonicEncode(ethutil.Bytes2Hex(k.PrivateKey)), " ")
    44  	}
    45  	return k.mnemonic
    46  }
    47  
    48  func (k *KeyPair) AsStrings() (string, string, string, string) {
    49  	return k.Mnemonic(), ethutil.Bytes2Hex(k.Address()), ethutil.Bytes2Hex(k.PrivateKey), ethutil.Bytes2Hex(k.PublicKey)
    50  }
    51  
    52  func (k *KeyPair) RlpEncode() []byte {
    53  	return k.RlpValue().Encode()
    54  }
    55  
    56  func (k *KeyPair) RlpValue() *ethutil.Value {
    57  	return ethutil.NewValue(k.PrivateKey)
    58  }