github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/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 "fmt" 39 "hash" 40 "io" 41 "math/big" 42 ) 43 44 var ( 45 ErrImport = fmt.Errorf("ecies: failed to import key") 46 ErrInvalidCurve = fmt.Errorf("ecies: invalid elliptic curve") 47 ErrInvalidParams = fmt.Errorf("ecies: invalid ECIES parameters") 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 ErrKeyDataTooLong = fmt.Errorf("ecies: can't supply requested key data") 142 ErrSharedTooLong = fmt.Errorf("ecies: shared secret is too long") 143 ErrInvalidMessage = fmt.Errorf("ecies: invalid message") 144 ) 145 146 var ( 147 big2To32 = new(big.Int).Exp(big.NewInt(2), big.NewInt(32), nil) 148 big2To32M1 = new(big.Int).Sub(big2To32, big.NewInt(1)) 149 ) 150 151 func incCounter(ctr []byte) { 152 if ctr[3]++; ctr[3] != 0 { 153 return 154 } 155 if ctr[2]++; ctr[2] != 0 { 156 return 157 } 158 if ctr[1]++; ctr[1] != 0 { 159 return 160 } 161 if ctr[0]++; ctr[0] != 0 { 162 return 163 } 164 } 165 166 // NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1). 167 func concatKDF(hash hash.Hash, z, s1 []byte, kdLen int) (k []byte, err error) { 168 if s1 == nil { 169 s1 = make([]byte, 0) 170 } 171 172 reps := ((kdLen + 7) * 8) / (hash.BlockSize() * 8) 173 if big.NewInt(int64(reps)).Cmp(big2To32M1) > 0 { 174 fmt.Println(big2To32M1) 175 return nil, ErrKeyDataTooLong 176 } 177 178 counter := []byte{0, 0, 0, 1} 179 k = make([]byte, 0) 180 181 for i := 0; i <= reps; i++ { 182 hash.Write(counter) 183 hash.Write(z) 184 hash.Write(s1) 185 k = append(k, hash.Sum(nil)...) 186 hash.Reset() 187 incCounter(counter) 188 } 189 190 k = k[:kdLen] 191 return 192 } 193 194 // messageTag computes the MAC of a message (called the tag) as per 195 // SEC 1, 3.5. 196 func messageTag(hash func() hash.Hash, km, msg, shared []byte) []byte { 197 mac := hmac.New(hash, km) 198 mac.Write(msg) 199 mac.Write(shared) 200 tag := mac.Sum(nil) 201 return tag 202 } 203 204 // Generate an initialisation vector for CTR mode. 205 func generateIV(params *ECIESParams, rand io.Reader) (iv []byte, err error) { 206 iv = make([]byte, params.BlockSize) 207 _, err = io.ReadFull(rand, iv) 208 return 209 } 210 211 // symEncrypt carries out CTR encryption using the block cipher specified in the 212 // parameters. 213 func symEncrypt(rand io.Reader, params *ECIESParams, key, m []byte) (ct []byte, err error) { 214 c, err := params.Cipher(key) 215 if err != nil { 216 return 217 } 218 219 iv, err := generateIV(params, rand) 220 if err != nil { 221 return 222 } 223 ctr := cipher.NewCTR(c, iv) 224 225 ct = make([]byte, len(m)+params.BlockSize) 226 copy(ct, iv) 227 ctr.XORKeyStream(ct[params.BlockSize:], m) 228 return 229 } 230 231 // symDecrypt carries out CTR decryption using the block cipher specified in 232 // the parameters 233 func symDecrypt(rand io.Reader, params *ECIESParams, key, ct []byte) (m []byte, err error) { 234 c, err := params.Cipher(key) 235 if err != nil { 236 return 237 } 238 239 ctr := cipher.NewCTR(c, ct[:params.BlockSize]) 240 241 m = make([]byte, len(ct)-params.BlockSize) 242 ctr.XORKeyStream(m, ct[params.BlockSize:]) 243 return 244 } 245 246 // Encrypt encrypts a message using ECIES as specified in SEC 1, 5.1. 247 // 248 // s1 and s2 contain shared information that is not part of the resulting 249 // ciphertext. s1 is fed into key derivation, s2 is fed into the MAC. If the 250 // shared information parameters aren't being used, they should be nil. 251 func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err error) { 252 params := pub.Params 253 if params == nil { 254 if params = ParamsFromCurve(pub.Curve); params == nil { 255 err = ErrUnsupportedECIESParameters 256 return 257 } 258 } 259 R, err := GenerateKey(rand, pub.Curve, params) 260 if err != nil { 261 return 262 } 263 264 hash := params.Hash() 265 z, err := R.GenerateShared(pub, params.KeyLen, params.KeyLen) 266 if err != nil { 267 return 268 } 269 K, err := concatKDF(hash, z, s1, params.KeyLen+params.KeyLen) 270 if err != nil { 271 return 272 } 273 Ke := K[:params.KeyLen] 274 Km := K[params.KeyLen:] 275 hash.Write(Km) 276 Km = hash.Sum(nil) 277 hash.Reset() 278 279 em, err := symEncrypt(rand, params, Ke, m) 280 if err != nil || len(em) <= params.BlockSize { 281 return 282 } 283 284 d := messageTag(params.Hash, Km, em, s2) 285 286 Rb := elliptic.Marshal(pub.Curve, R.PublicKey.X, R.PublicKey.Y) 287 ct = make([]byte, len(Rb)+len(em)+len(d)) 288 copy(ct, Rb) 289 copy(ct[len(Rb):], em) 290 copy(ct[len(Rb)+len(em):], d) 291 return 292 } 293 294 // Decrypt decrypts an ECIES ciphertext. 295 func (prv *PrivateKey) Decrypt(rand io.Reader, c, s1, s2 []byte) (m []byte, err error) { 296 if len(c) == 0 { 297 return nil, ErrInvalidMessage 298 } 299 params := prv.PublicKey.Params 300 if params == nil { 301 if params = ParamsFromCurve(prv.PublicKey.Curve); params == nil { 302 err = ErrUnsupportedECIESParameters 303 return 304 } 305 } 306 hash := params.Hash() 307 308 var ( 309 rLen int 310 hLen int = hash.Size() 311 mStart int 312 mEnd int 313 ) 314 315 switch c[0] { 316 case 2, 3, 4: 317 rLen = ((prv.PublicKey.Curve.Params().BitSize + 7) / 4) 318 if len(c) < (rLen + hLen + 1) { 319 err = ErrInvalidMessage 320 return 321 } 322 default: 323 err = ErrInvalidPublicKey 324 return 325 } 326 327 mStart = rLen 328 mEnd = len(c) - hLen 329 330 R := new(PublicKey) 331 R.Curve = prv.PublicKey.Curve 332 R.X, R.Y = elliptic.Unmarshal(R.Curve, c[:rLen]) 333 if R.X == nil { 334 err = ErrInvalidPublicKey 335 return 336 } 337 if !R.Curve.IsOnCurve(R.X, R.Y) { 338 err = ErrInvalidCurve 339 return 340 } 341 342 z, err := prv.GenerateShared(R, params.KeyLen, params.KeyLen) 343 if err != nil { 344 return 345 } 346 347 K, err := concatKDF(hash, z, s1, params.KeyLen+params.KeyLen) 348 if err != nil { 349 return 350 } 351 352 Ke := K[:params.KeyLen] 353 Km := K[params.KeyLen:] 354 hash.Write(Km) 355 Km = hash.Sum(nil) 356 hash.Reset() 357 358 d := messageTag(params.Hash, Km, c[mStart:mEnd], s2) 359 if subtle.ConstantTimeCompare(c[mEnd:], d) != 1 { 360 err = ErrInvalidMessage 361 return 362 } 363 364 m, err = symDecrypt(rand, params, Ke, c[mStart:mEnd]) 365 return 366 }