1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package subtle
import (
"bytes"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"math/big"
)
// ECPublicKey represents a elliptic curve public key.
type ECPublicKey struct {
elliptic.Curve
Point ECPoint
}
// ECPrivateKey represents a elliptic curve private key.
type ECPrivateKey struct {
PublicKey ECPublicKey
D *big.Int
}
// GetECPrivateKey converts a stored private key to ECPrivateKey.
func GetECPrivateKey(c elliptic.Curve, b []byte) *ECPrivateKey {
d := new(big.Int)
d.SetBytes(b)
x, y := c.Params().ScalarBaseMult(b)
pub := ECPublicKey{
Curve: c,
Point: ECPoint{
X: x,
Y: y,
},
}
return &ECPrivateKey{
PublicKey: pub,
D: d,
}
}
// ECPoint represents a point on the elliptic curve.
type ECPoint struct {
X, Y *big.Int
}
func (p *ECPrivateKey) getParams() *elliptic.CurveParams {
return p.PublicKey.Curve.Params()
}
func getModulus(c elliptic.Curve) *big.Int {
return c.Params().P
}
func fieldSizeInBits(c elliptic.Curve) int {
t := big.NewInt(1)
r := t.Sub(getModulus(c), t)
return r.BitLen()
}
func fieldSizeInBytes(c elliptic.Curve) int {
return (fieldSizeInBits(c) + 7) / 8
}
func encodingSizeInBytes(c elliptic.Curve, p string) (int, error) {
cSize := fieldSizeInBytes(c)
switch p {
case "UNCOMPRESSED":
return 2*cSize + 1, nil
case "DO_NOT_USE_CRUNCHY_UNCOMPRESSED":
return 2 * cSize, nil
case "COMPRESSED":
return cSize + 1, nil
}
return 0, fmt.Errorf("invalid point format :%s", p)
}
// PointEncode encodes a point into the format specified.
func PointEncode(c elliptic.Curve, pFormat string, pt ECPoint) ([]byte, error) {
if !c.IsOnCurve(pt.X, pt.Y) {
return nil, errors.New("curve check failed")
}
cSize := fieldSizeInBytes(c)
y := pt.Y.Bytes()
x := pt.X.Bytes()
switch pFormat {
case "UNCOMPRESSED":
encoded := make([]byte, 2*cSize+1)
copy(encoded[1+2*cSize-len(y):], y)
copy(encoded[1+cSize-len(x):], x)
encoded[0] = 4
return encoded, nil
case "DO_NOT_USE_CRUNCHY_UNCOMPRESSED":
encoded := make([]byte, 2*cSize)
if len(x) > cSize {
x = bytes.Replace(x, []byte("\x00"), []byte{}, -1)
}
if len(y) > cSize {
y = bytes.Replace(y, []byte("\x00"), []byte{}, -1)
}
copy(encoded[2*cSize-len(y):], y)
copy(encoded[cSize-len(x):], x)
return encoded, nil
case "COMPRESSED":
encoded := make([]byte, cSize+1)
copy(encoded[1+cSize-len(x):], x)
encoded[0] = 2
if pt.Y.Bit(0) > 0 {
encoded[0] = 3
}
return encoded, nil
}
return nil, errors.New("invalid point format")
}
// PointDecode decodes a encoded point to return an ECPoint
func PointDecode(c elliptic.Curve, pFormat string, e []byte) (*ECPoint, error) {
cSize := fieldSizeInBytes(c)
x, y := new(big.Int), new(big.Int)
switch pFormat {
case "UNCOMPRESSED":
if len(e) != (2*cSize + 1) {
return nil, errors.New("invalid point size")
}
if e[0] != 4 {
return nil, errors.New("invalid point format")
}
x.SetBytes(e[1 : cSize+1])
y.SetBytes(e[cSize+1:])
if !c.IsOnCurve(x, y) {
return nil, errors.New("invalid point")
}
return &ECPoint{
X: x,
Y: y,
}, nil
case "DO_NOT_USE_CRUNCHY_UNCOMPRESSED":
if len(e) != 2*cSize {
return nil, errors.New("invalid point size")
}
x.SetBytes(e[:cSize])
y.SetBytes(e[cSize:])
if !c.IsOnCurve(x, y) {
return nil, errors.New("invalid point")
}
return &ECPoint{
X: x,
Y: y,
}, nil
case "COMPRESSED":
if len(e) != cSize+1 {
return nil, errors.New("compressed point has wrong length")
}
lsb := false
if e[0] == 2 {
lsb = false
} else if e[0] == 3 {
lsb = true
} else {
return nil, errors.New("invalid format")
}
x := new(big.Int)
x.SetBytes(e[1:])
if (x.Sign() == -1) || (x.Cmp(c.Params().P) != -1) {
return nil, errors.New("x is out of range")
}
y := getY(x, lsb, c)
return &ECPoint{
X: x,
Y: y,
}, nil
}
return nil, fmt.Errorf("invalid format: %s", pFormat)
}
func getY(x *big.Int, lsb bool, c elliptic.Curve) *big.Int {
// y² = x³ - 3x + b
x3 := new(big.Int).Mul(x, x)
x3.Mul(x3, x)
threeX := new(big.Int).Lsh(x, 1)
threeX.Add(threeX, x)
b := c.Params().B
p := c.Params().P
x3.Sub(x3, threeX)
x3.Add(x3, b)
x3.ModSqrt(x3, p)
e := uint(1)
if lsb {
e = 0
}
if e == x3.Bit(0) {
x3 := x3.Sub(p, x3)
x3.Mod(x3, p)
}
return x3
}
func validatePublicPoint(pub *ECPoint, priv *ECPrivateKey) error {
if priv.PublicKey.Curve.IsOnCurve(pub.X, pub.Y) {
return nil
}
return errors.New("invalid public key")
}
// ComputeSharedSecret is used to compute a shared secret using given private key and peer public key.
func ComputeSharedSecret(pub *ECPoint, priv *ECPrivateKey) ([]byte, error) {
if err := validatePublicPoint(pub, priv); err != nil {
return nil, err
}
x, y := priv.PublicKey.Curve.ScalarMult(pub.X, pub.Y, priv.D.Bytes())
if x == nil {
return nil, errors.New("shared key compute error")
}
// check if x,y are on the curve
if err := validatePublicPoint(&ECPoint{X: x, Y: y}, priv); err != nil {
return nil, errors.New("invalid shared key")
}
sharedSecret := make([]byte, maxSharedKeyLength(priv.PublicKey))
return x.FillBytes(sharedSecret), nil
}
func maxSharedKeyLength(pub ECPublicKey) int {
return (pub.Curve.Params().BitSize + 7) / 8
}
// GenerateECDHKeyPair will create a new private key for a given curve.
func GenerateECDHKeyPair(c elliptic.Curve) (*ECPrivateKey, error) {
p, x, y, err := elliptic.GenerateKey(c, rand.Reader)
if err != nil {
return nil, err
}
return &ECPrivateKey{
PublicKey: ECPublicKey{
Curve: c,
Point: ECPoint{
X: x,
Y: y,
},
},
D: new(big.Int).SetBytes(p),
}, nil
}
// GetCurve returns the elliptic.Curve for a given standard curve name.
func GetCurve(c string) (elliptic.Curve, error) {
switch c {
case "secp224r1", "NIST_P224", "P-224":
return elliptic.P224(), nil
case "secp256r1", "NIST_P256", "P-256", "EllipticCurveType_NIST_P256":
return elliptic.P256(), nil
case "secp384r1", "NIST_P384", "P-384", "EllipticCurveType_NIST_P384":
return elliptic.P384(), nil
case "secp521r1", "NIST_P521", "P-521", "EllipticCurveType_NIST_P521":
return elliptic.P521(), nil
default:
return nil, errors.New("unsupported curve")
}
}
|