github.com/amazechain/amc@v0.1.3/common/crypto/ecies/ecies.go (about)

     1  // Copyright (c) 2013 Kyle Isom <kyle@tyrfingr.is>
     2  // Copyright (c) 2012 The Go Authors. All rights reserved.
     3  //
     4  // Redistribution and use in source and binary forms, with or without
     5  // modification, are permitted provided that the following conditions are
     6  // met:
     7  //
     8  //    * Redistributions of source code must retain the above copyright
     9  // notice, this list of conditions and the following disclaimer.
    10  //    * Redistributions in binary form must reproduce the above
    11  // copyright notice, this list of conditions and the following disclaimer
    12  // in the documentation and/or other materials provided with the
    13  // distribution.
    14  //    * Neither the name of Google Inc. nor the names of its
    15  // contributors may be used to endorse or promote products derived from
    16  // this software without specific prior written permission.
    17  //
    18  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    19  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    20  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    21  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    22  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    23  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    24  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    25  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    26  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    27  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    28  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    29  
    30  package ecies
    31  
    32  import (
    33  	"crypto/cipher"
    34  	"crypto/ecdsa"
    35  	"crypto/elliptic"
    36  	"crypto/hmac"
    37  	"crypto/subtle"
    38  	"encoding/binary"
    39  	"fmt"
    40  	"hash"
    41  	"io"
    42  	"math/big"
    43  )
    44  
    45  var (
    46  	ErrImport                     = fmt.Errorf("ecies: failed to import key")
    47  	ErrInvalidCurve               = fmt.Errorf("ecies: invalid elliptic curve")
    48  	ErrInvalidPublicKey           = fmt.Errorf("ecies: invalid public key")
    49  	ErrSharedKeyIsPointAtInfinity = fmt.Errorf("ecies: shared key is point at infinity")
    50  	ErrSharedKeyTooBig            = fmt.Errorf("ecies: shared key params are too big")
    51  )
    52  
    53  // PublicKey is a representation of an elliptic curve public key.
    54  type PublicKey struct {
    55  	X *big.Int
    56  	Y *big.Int
    57  	elliptic.Curve
    58  	Params *ECIESParams
    59  }
    60  
    61  // Export an ECIES public key as an ECDSA public key.
    62  func (pub *PublicKey) ExportECDSA() *ecdsa.PublicKey {
    63  	return &ecdsa.PublicKey{Curve: pub.Curve, X: pub.X, Y: pub.Y}
    64  }
    65  
    66  // Import an ECDSA public key as an ECIES public key.
    67  func ImportECDSAPublic(pub *ecdsa.PublicKey) *PublicKey {
    68  	return &PublicKey{
    69  		X:      pub.X,
    70  		Y:      pub.Y,
    71  		Curve:  pub.Curve,
    72  		Params: ParamsFromCurve(pub.Curve),
    73  	}
    74  }
    75  
    76  // PrivateKey is a representation of an elliptic curve private key.
    77  type PrivateKey struct {
    78  	PublicKey
    79  	D *big.Int
    80  }
    81  
    82  // Export an ECIES private key as an ECDSA private key.
    83  func (prv *PrivateKey) ExportECDSA() *ecdsa.PrivateKey {
    84  	pub := &prv.PublicKey
    85  	pubECDSA := pub.ExportECDSA()
    86  	return &ecdsa.PrivateKey{PublicKey: *pubECDSA, D: prv.D}
    87  }
    88  
    89  // Import an ECDSA private key as an ECIES private key.
    90  func ImportECDSA(prv *ecdsa.PrivateKey) *PrivateKey {
    91  	pub := ImportECDSAPublic(&prv.PublicKey)
    92  	return &PrivateKey{*pub, prv.D}
    93  }
    94  
    95  // Generate an elliptic curve public / private keypair. If params is nil,
    96  // the recommended default parameters for the key will be chosen.
    97  func GenerateKey(rand io.Reader, curve elliptic.Curve, params *ECIESParams) (prv *PrivateKey, err error) {
    98  	pb, x, y, err := elliptic.GenerateKey(curve, rand)
    99  	if err != nil {
   100  		return
   101  	}
   102  	prv = new(PrivateKey)
   103  	prv.PublicKey.X = x
   104  	prv.PublicKey.Y = y
   105  	prv.PublicKey.Curve = curve
   106  	prv.D = new(big.Int).SetBytes(pb)
   107  	if params == nil {
   108  		params = ParamsFromCurve(curve)
   109  	}
   110  	prv.PublicKey.Params = params
   111  	return
   112  }
   113  
   114  // MaxSharedKeyLength returns the maximum length of the shared key the
   115  // public key can produce.
   116  func MaxSharedKeyLength(pub *PublicKey) int {
   117  	return (pub.Curve.Params().BitSize + 7) / 8
   118  }
   119  
   120  // ECDH key agreement method used to establish secret keys for encryption.
   121  func (prv *PrivateKey) GenerateShared(pub *PublicKey, skLen, macLen int) (sk []byte, err error) {
   122  	if prv.PublicKey.Curve != pub.Curve {
   123  		return nil, ErrInvalidCurve
   124  	}
   125  	if skLen+macLen > MaxSharedKeyLength(pub) {
   126  		return nil, ErrSharedKeyTooBig
   127  	}
   128  
   129  	x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, prv.D.Bytes())
   130  	if x == nil {
   131  		return nil, ErrSharedKeyIsPointAtInfinity
   132  	}
   133  
   134  	sk = make([]byte, skLen+macLen)
   135  	skBytes := x.Bytes()
   136  	copy(sk[len(sk)-len(skBytes):], skBytes)
   137  	return sk, nil
   138  }
   139  
   140  var (
   141  	ErrSharedTooLong  = fmt.Errorf("ecies: shared secret is too long")
   142  	ErrInvalidMessage = fmt.Errorf("ecies: invalid message")
   143  )
   144  
   145  // NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1).
   146  func concatKDF(hash hash.Hash, z, s1 []byte, kdLen int) []byte {
   147  	counterBytes := make([]byte, 4)
   148  	k := make([]byte, 0, roundup(kdLen, hash.Size()))
   149  	for counter := uint32(1); len(k) < kdLen; counter++ {
   150  		binary.BigEndian.PutUint32(counterBytes, counter)
   151  		hash.Reset()
   152  		hash.Write(counterBytes)
   153  		hash.Write(z)
   154  		hash.Write(s1)
   155  		k = hash.Sum(k)
   156  	}
   157  	return k[:kdLen]
   158  }
   159  
   160  // roundup rounds size up to the next multiple of blocksize.
   161  func roundup(size, blocksize int) int {
   162  	return size + blocksize - (size % blocksize)
   163  }
   164  
   165  // deriveKeys creates the encryption and MAC keys using concatKDF.
   166  func deriveKeys(hash hash.Hash, z, s1 []byte, keyLen int) (Ke, Km []byte) {
   167  	K := concatKDF(hash, z, s1, 2*keyLen)
   168  	Ke = K[:keyLen]
   169  	Km = K[keyLen:]
   170  	hash.Reset()
   171  	hash.Write(Km)
   172  	Km = hash.Sum(Km[:0])
   173  	return Ke, Km
   174  }
   175  
   176  // messageTag computes the MAC of a message (called the tag) as per
   177  // SEC 1, 3.5.
   178  func messageTag(hash func() hash.Hash, km, msg, shared []byte) []byte {
   179  	mac := hmac.New(hash, km)
   180  	mac.Write(msg)
   181  	mac.Write(shared)
   182  	tag := mac.Sum(nil)
   183  	return tag
   184  }
   185  
   186  // Generate an initialisation vector for CTR mode.
   187  func generateIV(params *ECIESParams, rand io.Reader) (iv []byte, err error) {
   188  	iv = make([]byte, params.BlockSize)
   189  	_, err = io.ReadFull(rand, iv)
   190  	return
   191  }
   192  
   193  // symEncrypt carries out CTR encryption using the block cipher specified in the
   194  func symEncrypt(rand io.Reader, params *ECIESParams, key, m []byte) (ct []byte, err error) {
   195  	c, err := params.Cipher(key)
   196  	if err != nil {
   197  		return
   198  	}
   199  
   200  	iv, err := generateIV(params, rand)
   201  	if err != nil {
   202  		return
   203  	}
   204  	ctr := cipher.NewCTR(c, iv)
   205  
   206  	ct = make([]byte, len(m)+params.BlockSize)
   207  	copy(ct, iv)
   208  	ctr.XORKeyStream(ct[params.BlockSize:], m)
   209  	return
   210  }
   211  
   212  // symDecrypt carries out CTR decryption using the block cipher specified in
   213  // the parameters
   214  func symDecrypt(params *ECIESParams, key, ct []byte) (m []byte, err error) {
   215  	c, err := params.Cipher(key)
   216  	if err != nil {
   217  		return
   218  	}
   219  
   220  	ctr := cipher.NewCTR(c, ct[:params.BlockSize])
   221  
   222  	m = make([]byte, len(ct)-params.BlockSize)
   223  	ctr.XORKeyStream(m, ct[params.BlockSize:])
   224  	return
   225  }
   226  
   227  // Encrypt encrypts a message using ECIES as specified in SEC 1, 5.1.
   228  //
   229  // s1 and s2 contain shared information that is not part of the resulting
   230  // ciphertext. s1 is fed into key derivation, s2 is fed into the MAC. If the
   231  // shared information parameters aren't being used, they should be nil.
   232  func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err error) {
   233  	params, err := pubkeyParams(pub)
   234  	if err != nil {
   235  		return nil, err
   236  	}
   237  
   238  	R, err := GenerateKey(rand, pub.Curve, params)
   239  	if err != nil {
   240  		return nil, err
   241  	}
   242  
   243  	z, err := R.GenerateShared(pub, params.KeyLen, params.KeyLen)
   244  	if err != nil {
   245  		return nil, err
   246  	}
   247  
   248  	hash := params.Hash()
   249  	Ke, Km := deriveKeys(hash, z, s1, params.KeyLen)
   250  
   251  	em, err := symEncrypt(rand, params, Ke, m)
   252  	if err != nil || len(em) <= params.BlockSize {
   253  		return nil, err
   254  	}
   255  
   256  	d := messageTag(params.Hash, Km, em, s2)
   257  
   258  	Rb := elliptic.Marshal(pub.Curve, R.PublicKey.X, R.PublicKey.Y)
   259  	ct = make([]byte, len(Rb)+len(em)+len(d))
   260  	copy(ct, Rb)
   261  	copy(ct[len(Rb):], em)
   262  	copy(ct[len(Rb)+len(em):], d)
   263  	return ct, nil
   264  }
   265  
   266  // Decrypt decrypts an ECIES ciphertext.
   267  func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) {
   268  	if len(c) == 0 {
   269  		return nil, ErrInvalidMessage
   270  	}
   271  	params, err := pubkeyParams(&prv.PublicKey)
   272  	if err != nil {
   273  		return nil, err
   274  	}
   275  
   276  	hash := params.Hash()
   277  
   278  	var (
   279  		rLen   int
   280  		hLen   int = hash.Size()
   281  		mStart int
   282  		mEnd   int
   283  	)
   284  
   285  	switch c[0] {
   286  	case 2, 3, 4:
   287  		rLen = (prv.PublicKey.Curve.Params().BitSize + 7) / 4
   288  		if len(c) < (rLen + hLen + 1) {
   289  			return nil, ErrInvalidMessage
   290  		}
   291  	default:
   292  		return nil, ErrInvalidPublicKey
   293  	}
   294  
   295  	mStart = rLen
   296  	mEnd = len(c) - hLen
   297  
   298  	R := new(PublicKey)
   299  	R.Curve = prv.PublicKey.Curve
   300  	R.X, R.Y = elliptic.Unmarshal(R.Curve, c[:rLen])
   301  	if R.X == nil {
   302  		return nil, ErrInvalidPublicKey
   303  	}
   304  
   305  	z, err := prv.GenerateShared(R, params.KeyLen, params.KeyLen)
   306  	if err != nil {
   307  		return nil, err
   308  	}
   309  	Ke, Km := deriveKeys(hash, z, s1, params.KeyLen)
   310  
   311  	d := messageTag(params.Hash, Km, c[mStart:mEnd], s2)
   312  	if subtle.ConstantTimeCompare(c[mEnd:], d) != 1 {
   313  		return nil, ErrInvalidMessage
   314  	}
   315  
   316  	return symDecrypt(params, Ke, c[mStart:mEnd])
   317  }