示例#1
0
func benchDouble(curve elliptic.Curve, n int) {
	x := curve.Params().Gx
	y := curve.Params().Gy
	for i := 0; i < n; i++ {
		curve.Double(x, y)
	}
}
示例#2
0
func benchScalarMult(curve elliptic.Curve, k []byte, n int) {
	x := curve.Params().Gx
	y := curve.Params().Gy
	for i := 0; i < n; i++ {
		curve.ScalarMult(x, y, k)
	}
}
示例#3
0
func benchAdd(curve elliptic.Curve, n int) {
	x := curve.Params().Gx
	y := curve.Params().Gy
	for i := 0; i < n; i++ {
		curve.Add(x, y, x, y)
	}
}
示例#4
0
// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
// The OID for the named curve may be provided from another source (such as
// the PKCS8 container) - if it is provided then use this instead of the OID
// that may exist in the EC private key structure.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
	var privKey ecPrivateKey
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
	}
	if privKey.Version != ecPrivKeyVersion {
		return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
	}

	var curve elliptic.Curve
	if namedCurveOID != nil {
		curve = namedCurveFromOID(*namedCurveOID)
	} else {
		curve = namedCurveFromOID(privKey.NamedCurveOID)
	}
	if curve == nil {
		return nil, errors.New("x509: unknown elliptic curve")
	}

	k := new(big.Int).SetBytes(privKey.PrivateKey)
	if k.Cmp(curve.Params().N) >= 0 {
		return nil, errors.New("x509: invalid elliptic curve private key value")
	}
	priv := new(ecdsa.PrivateKey)
	priv.Curve = curve
	priv.D = k
	priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey)

	return priv, nil
}
示例#5
0
文件: jwt.go 项目: knq/jwt
// getSuitableAlgFromCurve inspects the key length in curve, and determines the
// corresponding jwt.Algorithm.
func getSuitableAlgFromCurve(curve elliptic.Curve) (jwt.Algorithm, error) {
	curveBitSize := curve.Params().BitSize

	// compute curve key len
	keyLen := curveBitSize / 8
	if curveBitSize%8 > 0 {
		keyLen++
	}

	// determine alg
	var alg jwt.Algorithm
	switch 2 * keyLen {
	case 64:
		alg = jwt.ES256
	case 96:
		alg = jwt.ES384
	case 132:
		alg = jwt.ES512

	default:
		return jwt.NONE, fmt.Errorf("invalid key length %d", keyLen)
	}

	return alg, nil
}
示例#6
0
文件: ballot.go 项目: wbl/mozvote
func UnmarshalBallot(c elliptic.Curve, bytes []byte) (*Ballot, error) {
	if len(bytes) < 4 {
		return nil, errors.New("Not long enough!")
	}
	numballots := int(bytes[0])<<24 + int(bytes[1])<<16 +
		int(bytes[2])<<8 + int(bytes[3])
	ret := new(Ballot)
	ret.boxes = make([]*Checkbox, numballots, numballots)
	bytesize := (c.Params().BitSize + 7) >> 3
	ballotlen := 2 + 8*bytesize
	if len(bytes) != 4+numballots*ballotlen+2*bytesize {
		return nil, errors.New("Wrong length!")
	}
	for i := 0; i < numballots; i++ {
		ret.boxes[i] = UnmarshalCheckbox(c, bytes[i*ballotlen+4:(i+1)*ballotlen+4])
		if ret.boxes[i] == nil {
			return nil, errors.New("Incorrect serialization")
		}
	}
	ret.c = new(big.Int)
	ret.c.SetBytes(bytes[numballots*ballotlen+4 : numballots*ballotlen+
		4+bytesize])
	ret.r = new(big.Int)
	ret.r.SetBytes(bytes[numballots*ballotlen+4+bytesize : numballots*ballotlen+4+2*bytesize])
	return ret, nil
}
示例#7
0
文件: jwk.go 项目: ericchiang/dex
func (key rawJSONWebKey) ecPrivateKey() (*ecdsa.PrivateKey, error) {
	var curve elliptic.Curve
	switch key.Crv {
	case "P-256":
		curve = elliptic.P256()
	case "P-384":
		curve = elliptic.P384()
	case "P-521":
		curve = elliptic.P521()
	default:
		return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv)
	}

	if key.X == nil || key.Y == nil || key.D == nil {
		return nil, fmt.Errorf("square/go-jose: invalid EC private key, missing x/y/d values")
	}

	x := key.X.bigInt()
	y := key.Y.bigInt()

	if !curve.IsOnCurve(x, y) {
		return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve")
	}

	return &ecdsa.PrivateKey{
		PublicKey: ecdsa.PublicKey{
			Curve: curve,
			X:     x,
			Y:     y,
		},
		D: key.D.bigInt(),
	}, nil
}
示例#8
0
文件: urs.go 项目: eXcomm/urs
func hashG(c elliptic.Curve, m []byte) (hx, hy *big.Int) {
	h := sha256.New()
	h.Write(m)
	d := h.Sum(nil)
	hx, hy = c.ScalarBaseMult(d) // g^H'()
	return
}
示例#9
0
文件: signature.go 项目: decred/dcrd
// https://tools.ietf.org/html/rfc6979#section-2.3.4
func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte {
	z1 := hashToInt(in, curve)
	z2 := new(big.Int).Sub(z1, curve.Params().N)
	if z2.Sign() < 0 {
		return int2octets(z1, rolen)
	}
	return int2octets(z2, rolen)
}
示例#10
0
// kexECDH performs Elliptic Curve Diffie-Hellman key exchange as
// described in RFC 5656, section 4.
func (c *ClientConn) kexECDH(curve elliptic.Curve, magics *handshakeMagics, hostKeyAlgo string) (*kexResult, error) {
	ephKey, err := ecdsa.GenerateKey(curve, c.config.rand())
	if err != nil {
		return nil, err
	}

	kexInit := kexECDHInitMsg{
		ClientPubKey: elliptic.Marshal(curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
	}

	serialized := marshal(msgKexECDHInit, kexInit)
	if err := c.writePacket(serialized); err != nil {
		return nil, err
	}

	packet, err := c.readPacket()
	if err != nil {
		return nil, err
	}

	var reply kexECDHReplyMsg
	if err = unmarshal(&reply, packet, msgKexECDHReply); err != nil {
		return nil, err
	}

	x, y := elliptic.Unmarshal(curve, reply.EphemeralPubKey)
	if x == nil {
		return nil, errors.New("ssh: elliptic.Unmarshal failure")
	}
	if !validateECPublicKey(curve, x, y) {
		return nil, errors.New("ssh: ephemeral server key not on curve")
	}

	// generate shared secret
	secret, _ := curve.ScalarMult(x, y, ephKey.D.Bytes())

	hashFunc := ecHash(curve)
	h := hashFunc.New()
	writeString(h, magics.clientVersion)
	writeString(h, magics.serverVersion)
	writeString(h, magics.clientKexInit)
	writeString(h, magics.serverKexInit)
	writeString(h, reply.HostKey)
	writeString(h, kexInit.ClientPubKey)
	writeString(h, reply.EphemeralPubKey)
	K := make([]byte, intLength(secret))
	marshalInt(K, secret)
	h.Write(K)

	return &kexResult{
		H:         h.Sum(nil),
		K:         K,
		HostKey:   reply.HostKey,
		Signature: reply.Signature,
		Hash:      hashFunc,
	}, nil
}
示例#11
0
func testKeyGeneration(t *testing.T, c elliptic.Curve, tag string) {
	priv, err := GenerateKey(c, rand.Reader)
	if err != nil {
		t.Errorf("%s: error: %s", tag, err)
		return
	}
	if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) {
		t.Errorf("%s: public key invalid: %s", tag, err)
	}
}
示例#12
0
// ecHash returns the hash to match the given elliptic curve, see RFC
// 5656, section 6.2.1
func ecHash(curve elliptic.Curve) crypto.Hash {
	bitSize := curve.Params().BitSize
	switch {
	case bitSize <= 256:
		return crypto.SHA256
	case bitSize <= 384:
		return crypto.SHA384
	}
	return crypto.SHA512
}
示例#13
0
文件: checkbox.go 项目: wbl/mozvote
func MarshalMark(c elliptic.Curve, m *Mark) []byte {
	bytelen := (c.Params().BitSize + 7) >> 3
	pointlen := 1 + 2*bytelen
	outlen := 2 * pointlen
	ret := make([]byte, outlen, outlen)
	abytes := elliptic.Marshal(c, m.ax, m.ay)
	copy(ret, abytes)
	bbytes := elliptic.Marshal(c, m.bx, m.by)
	copy(ret[pointlen:], bbytes)
	return ret
}
示例#14
0
文件: checkbox.go 项目: wbl/mozvote
func UnmarshalMark(c elliptic.Curve, bytes []byte) *Mark {
	bytelen := (c.Params().BitSize + 7) >> 3
	pointlen := 1 + 2*bytelen
	if len(bytes) != 2*pointlen {
		return nil
	}
	ret := new(Mark)
	ret.ax, ret.ay = elliptic.Unmarshal(c, bytes[:pointlen])
	ret.bx, ret.by = elliptic.Unmarshal(c, bytes[pointlen:2*pointlen])
	return ret
}
示例#15
0
// Marshal encodes a ECC Point into it's compressed representation
func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {
	byteLen := (curve.Params().BitSize + 7) >> 3

	ret := make([]byte, 1+byteLen)
	ret[0] = 2 + byte(y.Bit(0))

	xBytes := x.Bytes()
	copy(ret[1+byteLen-len(xBytes):], xBytes)

	return ret
}
示例#16
0
// GoodCurve determines if an elliptic curve meets our requirements.
func (policy *KeyPolicy) goodCurve(c elliptic.Curve) (err error) {
	// Simply use a whitelist for now.
	params := c.Params()
	switch {
	case policy.AllowECDSANISTP256 && params == elliptic.P256().Params():
		return nil
	case policy.AllowECDSANISTP384 && params == elliptic.P384().Params():
		return nil
	default:
		return core.MalformedRequestError(fmt.Sprintf("ECDSA curve %v not allowed", params.Name))
	}
}
示例#17
0
文件: key.go 项目: AaronGoldman/ccfs
// Unmarshal converts a point, serialized by Marshal, into an x, y pair.
// It is an error if the point is not on the curve. On error, x = nil.
func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {
	byteLen := (curve.Params().BitSize + 7) >> 3
	if len(data) != 1+2*byteLen {
		return
	}
	if data[0] != 4 { // uncompressed form
		return
	}
	x = new(big.Int).SetBytes(data[1 : 1+byteLen])
	y = new(big.Int).SetBytes(data[1+byteLen:])
	return
}
示例#18
0
// GenerateKey generates a public and private key pair.
func GenerateKey(c elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error) {
	k, err := randFieldElement(c, rand)
	if err != nil {
		return
	}

	priv = new(PrivateKey)
	priv.PublicKey.Curve = c
	priv.D = k
	priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
	return
}
示例#19
0
文件: util.go 项目: rf152/boulder
// Get size of curve in bytes
func curveSize(crv elliptic.Curve) int {
	bits := crv.Params().BitSize

	div := bits / 8
	mod := bits % 8

	if mod == 0 {
		return div
	}

	return div + 1
}
示例#20
0
func parseECCoordinate(cB64Url string, curve elliptic.Curve) (*big.Int, error) {
	curveByteLen := (curve.Params().BitSize + 7) >> 3

	cBytes, err := joseBase64UrlDecode(cB64Url)
	if err != nil {
		return nil, fmt.Errorf("invalid base64 URL encoding: %s", err)
	}
	cByteLength := len(cBytes)
	if cByteLength != curveByteLen {
		return nil, fmt.Errorf("invalid number of octets: got %d, should be %d", cByteLength, curveByteLen)
	}
	return new(big.Int).SetBytes(cBytes), nil
}
示例#21
0
// randFieldElement returns a random element of the field underlying the given
// curve using the procedure given in [NSA] A.2.1.
func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
	params := c.Params()
	b := make([]byte, params.BitSize/8+8)
	_, err = io.ReadFull(rand, b)
	if err != nil {
		return
	}

	k = new(big.Int).SetBytes(b)
	n := new(big.Int).Sub(params.N, one)
	k.Mod(k, n)
	k.Add(k, one)
	return
}
示例#22
0
// hashToInt converts a hash value to an integer. There is some disagreement
// about how this is done. [NSA] suggests that this is done in the obvious
// manner, but [SECG] truncates the hash to the bit-length of the curve order
// first. We follow [SECG] because that's what OpenSSL does. Additionally,
// OpenSSL right shifts excess bits from the number if the hash is too large
// and we mirror that too.
func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
	orderBits := c.Params().N.BitLen()
	orderBytes := (orderBits + 7) / 8
	if len(hash) > orderBytes {
		hash = hash[:orderBytes]
	}

	ret := new(big.Int).SetBytes(hash)
	excess := len(hash)*8 - orderBits
	if excess > 0 {
		ret.Rsh(ret, uint(excess))
	}
	return ret
}
示例#23
0
文件: log.go 项目: wbl/mozvote
func DiscreteLog(x *big.Int, y *big.Int, c elliptic.Curve, bound int) (int, error) {
	var xprime *big.Int
	var yprime *big.Int
	if x.Cmp(big.NewInt(0)) == 0 && y.Cmp(big.NewInt(0)) == 0 {
		return 0, nil
	}
	for i := 0; i < bound; i++ {
		xprime, yprime = c.ScalarBaseMult(big.NewInt(int64(i)).Bytes())
		if xprime.Cmp(x) == 0 && yprime.Cmp(y) == 0 {
			return i, nil
		}
	}
	return -1, errors.New("log not found")
}
示例#24
0
文件: ecc.go 项目: knq/jwt
// NewEllipticSigner creates an Elliptic Curve Signer for the specified curve.
func NewEllipticSigner(alg Algorithm, curve elliptic.Curve) func(pemutil.Store, crypto.Hash) (Signer, error) {
	curveBitSize := curve.Params().BitSize

	// precompute curve key len
	keyLen := curveBitSize / 8
	if curveBitSize%8 > 0 {
		keyLen++
	}

	return func(store pemutil.Store, hash crypto.Hash) (Signer, error) {
		var ok bool
		var privRaw, pubRaw interface{}
		var priv *ecdsa.PrivateKey
		var pub *ecdsa.PublicKey

		// check private key
		if privRaw, ok = store[pemutil.ECPrivateKey]; ok {
			if priv, ok = privRaw.(*ecdsa.PrivateKey); !ok {
				return nil, errors.New("NewEllipticSigner: private key must be a *ecdsa.PrivateKey")
			}

			// check curve type matches private key curve type
			if curveBitSize != priv.Curve.Params().BitSize {
				return nil, fmt.Errorf("NewEllipticSigner: private key have bit size %d", curve.Params().BitSize)
			}
		}

		// check public key
		if pubRaw, ok = store[pemutil.PublicKey]; ok {
			if pub, ok = pubRaw.(*ecdsa.PublicKey); !ok {
				return nil, errors.New("NewEllipticSigner: public key must be a *ecdsa.PublicKey")
			}
		}

		// check that either a private or public key has been provided
		if priv == nil && pub == nil {
			return nil, errors.New("NewEllipticSigner: either a private key or a public key must be provided")
		}

		return &eccSigner{
			alg:    alg,
			curve:  curve,
			hash:   hash,
			priv:   priv,
			pub:    pub,
			keyLen: keyLen,
		}, nil
	}
}
示例#25
0
文件: privkey.go 项目: Roasbeef/btcd
// PrivKeyFromBytes returns a private and public key for `curve' based on the
// private key passed as an argument as a byte slice.
func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey,
	*PublicKey) {
	x, y := curve.ScalarBaseMult(pk)

	priv := &ecdsa.PrivateKey{
		PublicKey: ecdsa.PublicKey{
			Curve: curve,
			X:     x,
			Y:     y,
		},
		D: new(big.Int).SetBytes(pk),
	}

	return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
}
示例#26
0
文件: ballot.go 项目: wbl/mozvote
func MarshalReckoning(c elliptic.Curve, r *Reckoning) []byte {
	num := len(r.marks)
	bytesize := (c.Params().BitSize + 7) >> 3
	marklen := 2 + 4*bytesize
	totsize := 4 + marklen*num
	ret := make([]byte, totsize, totsize)
	ret[0] = byte((num >> 24) & 0xff)
	ret[1] = byte((num >> 16) & 0xff)
	ret[2] = byte((num >> 8) & 0xff)
	ret[3] = byte((num) & 0xff)
	for i := 0; i < num; i++ {
		copy(ret[i*marklen+4:(i+1)*marklen+4], MarshalMark(c, r.marks[i]))
	}
	return ret
}
示例#27
0
文件: checkbox.go 项目: wbl/mozvote
func DecryptMark(c elliptic.Curve, m *Mark, priv []byte) (int, error) {
	tx, ty := c.ScalarMult(m.ax, m.ay, priv)
	tm := big.NewInt(0)
	tm.Sub(c.Params().P, ty)
	tm.Mod(tm, c.Params().P)
	px, py := c.Add(m.bx, m.by, tx, tm)
	return DiscreteLog(px, py, c, 1<<10)
}
示例#28
0
文件: checkbox.go 项目: wbl/mozvote
func SumMarks(c elliptic.Curve, marks [](*Mark)) *Mark {
	ax := marks[0].ax
	ay := marks[0].ay
	bx := marks[0].bx
	by := marks[0].by
	for i := 1; i < len(marks); i++ {
		ax, ay = c.Add(ax, ay, marks[i].ax, marks[i].ay)
		bx, by = c.Add(bx, by, marks[i].bx, marks[i].by)
	}
	r := new(Mark)
	r.ax = ax
	r.ay = ay
	r.bx = bx
	r.by = by
	return r
}
示例#29
0
文件: sec1.go 项目: RajibTheKing/gcc
// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
// The OID for the named curve may be provided from another source (such as
// the PKCS8 container) - if it is provided then use this instead of the OID
// that may exist in the EC private key structure.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
	var privKey ecPrivateKey
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
	}
	if privKey.Version != ecPrivKeyVersion {
		return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
	}

	var curve elliptic.Curve
	if namedCurveOID != nil {
		curve = namedCurveFromOID(*namedCurveOID)
	} else {
		curve = namedCurveFromOID(privKey.NamedCurveOID)
	}
	if curve == nil {
		return nil, errors.New("x509: unknown elliptic curve")
	}

	k := new(big.Int).SetBytes(privKey.PrivateKey)
	curveOrder := curve.Params().N
	if k.Cmp(curveOrder) >= 0 {
		return nil, errors.New("x509: invalid elliptic curve private key value")
	}
	priv := new(ecdsa.PrivateKey)
	priv.Curve = curve
	priv.D = k

	privateKey := make([]byte, (curveOrder.BitLen()+7)/8)

	// Some private keys have leading zero padding. This is invalid
	// according to [SEC1], but this code will ignore it.
	for len(privKey.PrivateKey) > len(privateKey) {
		if privKey.PrivateKey[0] != 0 {
			return nil, errors.New("x509: invalid private key length")
		}
		privKey.PrivateKey = privKey.PrivateKey[1:]
	}

	// Some private keys remove all leading zeros, this is also invalid
	// according to [SEC1] but since OpenSSL used to do this, we ignore
	// this too.
	copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
	priv.X, priv.Y = curve.ScalarBaseMult(privateKey)

	return priv, nil
}
示例#30
0
文件: ballot.go 项目: wbl/mozvote
func UnmarshalReckoning(c elliptic.Curve, bytes []byte) (*Reckoning, error) {
	if len(bytes) < 4 {
		return nil, errors.New("Insufficient length")
	}
	num := int(bytes[0])<<24 + int(bytes[1])<<16 + int(bytes[2])<<8 + int(bytes[3])
	bytesize := (c.Params().BitSize + 7) >> 3
	marklen := 2 + 4*bytesize
	if len(bytes) != marklen*num+4 {
		return nil, errors.New("Incorrect length")
	}
	ret := new(Reckoning)
	ret.marks = make([]*Mark, num, num)
	for i := 0; i < num; i++ {
		ret.marks[i] = UnmarshalMark(c, bytes[i*marklen+4:(i+1)*marklen+4])
	}
	return ret, nil
}