keypair.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package crypto
  17. import (
  18. "strings"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  21. )
  22. type KeyPair struct {
  23. PrivateKey []byte
  24. PublicKey []byte
  25. address []byte
  26. mnemonic string
  27. // The associated account
  28. // account *StateObject
  29. }
  30. func GenerateNewKeyPair() *KeyPair {
  31. _, prv := secp256k1.GenerateKeyPair()
  32. keyPair, _ := NewKeyPairFromSec(prv) // swallow error, this one cannot err
  33. return keyPair
  34. }
  35. func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) {
  36. pubkey, err := secp256k1.GeneratePubKey(seckey)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return &KeyPair{PrivateKey: seckey, PublicKey: pubkey}, nil
  41. }
  42. func (k *KeyPair) Address() []byte {
  43. if k.address == nil {
  44. k.address = Sha3(k.PublicKey[1:])[12:]
  45. }
  46. return k.address
  47. }
  48. func (k *KeyPair) Mnemonic() string {
  49. if k.mnemonic == "" {
  50. k.mnemonic = strings.Join(MnemonicEncode(common.Bytes2Hex(k.PrivateKey)), " ")
  51. }
  52. return k.mnemonic
  53. }
  54. func (k *KeyPair) AsStrings() (string, string, string, string) {
  55. return k.Mnemonic(), common.Bytes2Hex(k.Address()), common.Bytes2Hex(k.PrivateKey), common.Bytes2Hex(k.PublicKey)
  56. }