github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/crypto/crypto.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library 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  // The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package crypto
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/elliptic"
    22  	"crypto/rand"
    23  	"encoding/hex"
    24  	"errors"
    25  	"fmt"
    26  	"io"
    27  	"io/ioutil"
    28  	"math/big"
    29  	"os"
    30  
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/common/math"
    33  	"github.com/ethereum/go-ethereum/crypto/sha3"
    34  	"github.com/ethereum/go-ethereum/rlp"
    35  )
    36  
    37  var (
    38  	secp256k1_N, _  = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    39  	secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2))
    40  )
    41  
    42  // Keccak256 calculates and returns the Keccak256 hash of the input data.
    43  func Keccak256(data ...[]byte) []byte {
    44  	d := sha3.NewKeccak256()
    45  	for _, b := range data {
    46  		d.Write(b)
    47  	}
    48  	return d.Sum(nil)
    49  }
    50  
    51  // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
    52  // converting it to an internal Hash data structure.
    53  func Keccak256Hash(data ...[]byte) (h common.Hash) {
    54  	d := sha3.NewKeccak256()
    55  	for _, b := range data {
    56  		d.Write(b)
    57  	}
    58  	d.Sum(h[:0])
    59  	return h
    60  }
    61  
    62  // Keccak512 calculates and returns the Keccak512 hash of the input data.
    63  func Keccak512(data ...[]byte) []byte {
    64  	d := sha3.NewKeccak512()
    65  	for _, b := range data {
    66  		d.Write(b)
    67  	}
    68  	return d.Sum(nil)
    69  }
    70  
    71  // Creates an ethereum address given the bytes and the nonce
    72  func CreateAddress(b common.Address, nonce uint64) common.Address {
    73  	data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
    74  	return common.BytesToAddress(Keccak256(data)[12:])
    75  }
    76  
    77  // ToECDSA creates a private key with the given D value.
    78  func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
    79  	return toECDSA(d, true)
    80  }
    81  
    82  // ToECDSAUnsafe blidly converts a binary blob to a private key. It should almost
    83  // never be used unless you are sure the input is valid and want to avoid hitting
    84  // errors due to bad origin encoding (0 prefixes cut off).
    85  func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
    86  	priv, _ := toECDSA(d, false)
    87  	return priv
    88  }
    89  
    90  // toECDSA creates a private key with the given D value. The strict parameter
    91  // controls whether the key's length should be enforced at the curve size or
    92  // it can also accept legacy encodings (0 prefixes).
    93  func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
    94  	priv := new(ecdsa.PrivateKey)
    95  	priv.PublicKey.Curve = S256()
    96  	if strict && 8*len(d) != priv.Params().BitSize {
    97  		return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
    98  	}
    99  	priv.D = new(big.Int).SetBytes(d)
   100  	priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
   101  	return priv, nil
   102  }
   103  
   104  // FromECDSA exports a private key into a binary dump.
   105  func FromECDSA(priv *ecdsa.PrivateKey) []byte {
   106  	if priv == nil {
   107  		return nil
   108  	}
   109  	return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
   110  }
   111  
   112  func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
   113  	if len(pub) == 0 {
   114  		return nil
   115  	}
   116  	x, y := elliptic.Unmarshal(S256(), pub)
   117  	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}
   118  }
   119  
   120  func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
   121  	if pub == nil || pub.X == nil || pub.Y == nil {
   122  		return nil
   123  	}
   124  	return elliptic.Marshal(S256(), pub.X, pub.Y)
   125  }
   126  
   127  // HexToECDSA parses a secp256k1 private key.
   128  func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
   129  	b, err := hex.DecodeString(hexkey)
   130  	if err != nil {
   131  		return nil, errors.New("invalid hex string")
   132  	}
   133  	return ToECDSA(b)
   134  }
   135  
   136  // LoadECDSA loads a secp256k1 private key from the given file.
   137  func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
   138  	buf := make([]byte, 64)
   139  	fd, err := os.Open(file)
   140  	if err != nil {
   141  		return nil, err
   142  	}
   143  	defer fd.Close()
   144  	if _, err := io.ReadFull(fd, buf); err != nil {
   145  		return nil, err
   146  	}
   147  
   148  	key, err := hex.DecodeString(string(buf))
   149  	if err != nil {
   150  		return nil, err
   151  	}
   152  	return ToECDSA(key)
   153  }
   154  
   155  // SaveECDSA saves a secp256k1 private key to the given file with
   156  // restrictive permissions. The key data is saved hex-encoded.
   157  func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
   158  	k := hex.EncodeToString(FromECDSA(key))
   159  	return ioutil.WriteFile(file, []byte(k), 0600)
   160  }
   161  
   162  func GenerateKey() (*ecdsa.PrivateKey, error) {
   163  	return ecdsa.GenerateKey(S256(), rand.Reader)
   164  }
   165  
   166  // ValidateSignatureValues verifies whether the signature values are valid with
   167  // the given chain rules. The v value is assumed to be either 0 or 1.
   168  func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
   169  	if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
   170  		return false
   171  	}
   172  	// reject upper range of s values (ECDSA malleability)
   173  	// see discussion in secp256k1/libsecp256k1/include/secp256k1.h
   174  	if homestead && s.Cmp(secp256k1_halfN) > 0 {
   175  		return false
   176  	}
   177  	// Frontier: allow s to be in full N range
   178  	return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1)
   179  }
   180  
   181  func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
   182  	pubBytes := FromECDSAPub(&p)
   183  	return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
   184  }
   185  
   186  func zeroBytes(bytes []byte) {
   187  	for i := range bytes {
   188  		bytes[i] = 0
   189  	}
   190  }