Golang crypto-elliptic.P256类(方法)实例源码

下面列出了Golang crypto-elliptic.P256 类(方法)源码代码实例,从而了解它的用法。

作者:tmroede    项目:cloudprox   
// UnmarshalSignerProto decodes a signing key from a CryptoKey protobuf
// message.
func UnmarshalSignerProto(ck *CryptoKey) (*Signer, error) {
	if *ck.Version != CryptoVersion_CRYPTO_VERSION_1 {
		return nil, newError("bad version")
	}

	if *ck.Purpose != CryptoKey_SIGNING {
		return nil, newError("bad purpose")
	}

	if *ck.Algorithm != CryptoKey_ECDSA_SHA {
		return nil, newError("bad algorithm")
	}

	k := new(ECDSA_SHA_SigningKeyV1)
	defer ZeroBytes(k.EcPrivate)
	if err := proto.Unmarshal(ck.Key, k); err != nil {
		return nil, err
	}

	if *k.Curve != NamedEllipticCurve_PRIME256_V1 {
		return nil, newError("bad Curve")
	}

	s := new(Signer)
	s.ec = new(ecdsa.PrivateKey)
	s.ec.D = new(big.Int).SetBytes(k.EcPrivate)
	s.ec.Curve = elliptic.P256()
	s.ec.X, s.ec.Y = elliptic.Unmarshal(elliptic.P256(), k.EcPublic)
	if s.ec.X == nil || s.ec.Y == nil {
		return nil, fmt.Errorf("failed to unmarshal EC point: X=%v, Y=%v", s.ec.X, s.ec.Y)
	}

	return s, nil
}

作者:tmroede    项目:cloudprox   
// UnmarshalVerifierProto decodes a verifying key from a CryptoKey protobuf
// message.
func UnmarshalVerifierProto(ck *CryptoKey) (*Verifier, error) {
	if *ck.Version != CryptoVersion_CRYPTO_VERSION_1 {
		return nil, newError("bad version")
	}

	if *ck.Purpose != CryptoKey_VERIFYING {
		return nil, newError("bad purpose")
	}

	if *ck.Algorithm != CryptoKey_ECDSA_SHA {
		return nil, newError("bad algorithm")
	}

	k := new(ECDSA_SHA_VerifyingKeyV1)
	if err := proto.Unmarshal(ck.Key, k); err != nil {
		return nil, err
	}

	if *k.Curve != NamedEllipticCurve_PRIME256_V1 {
		return nil, newError("bad curve")
	}

	s := new(Verifier)
	s.ec = new(ecdsa.PublicKey)
	s.ec.Curve = elliptic.P256()
	s.ec.X, s.ec.Y = elliptic.Unmarshal(elliptic.P256(), k.EcPublic)
	return s, nil
}

作者:jmptrade    项目:gocrypt   
func TestBadPubs(t *testing.T) {
	priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bad1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bad2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
	bad2.Curve = elliptic.P521()

	var bad3 *ecdsa.PublicKey
	if _, err = ECDH(priv, bad3); err == nil {
		t.Fatalf("ECDH should fail with nil key")
	} else if _, err = ECDH(priv, &bad1.PublicKey); err == nil {
		t.Fatalf("ECDH should fail with mismatched curve")
	} else if _, err = ECDH(priv, &bad2.PublicKey); err == nil {
		t.Fatalf("ECDH should fail with wrong curve")
	}
}

作者:kyonetc    项目:em   
// Encrypt plainText into an Encrypted Published Message using the given private key.
func EncryptPub(log chan string, src_privkey []byte, plainText string) *EncryptedMessage {
	// Generate New Public/Private Key Pair
	D1, X1, Y1 := CreateKey(log)

	// Point Multiply to get new Pubkey
	PubX, PubY := elliptic.P256().ScalarMult(X1, Y1, src_privkey)

	// Generate Pubkey hashes
	PubHash := sha512.Sum512(elliptic.Marshal(elliptic.P256(), PubX, PubY))
	PubHash_E := PubHash[:32]
	PubHash_M := PubHash[32:64]

	IV, cipherText, _ := SymmetricEncrypt(PubHash_E, plainText)

	// Generate HMAC
	mac := hmac.New(sha256.New, PubHash_M)
	mac.Write(cipherText)
	HMAC := mac.Sum(nil)

	ret := new(EncryptedMessage)
	copy(ret.IV[:], IV[:])
	copy(ret.PublicKey[:32], D1)
	ret.CipherText = cipherText
	copy(ret.HMAC[:], HMAC)

	return ret
}

作者:kevinawals    项目:cloudprox   
// UnmarshalSignerProto decodes a signing key from a CryptoKey protobuf
// message.
func UnmarshalSignerProto(ck *CryptoKey) (*Signer, error) {
	if *ck.Version != CryptoVersion_CRYPTO_VERSION_1 {
		return nil, newError("bad version")
	}

	if *ck.Purpose != CryptoKey_SIGNING {
		return nil, newError("bad purpose")
	}

	if *ck.Algorithm != CryptoKey_ECDSA_SHA {
		return nil, newError("bad algorithm")
	}

	var k ECDSA_SHA_SigningKeyV1
	defer ZeroBytes(k.EcPrivate)
	if err := proto.Unmarshal(ck.Key, &k); err != nil {
		return nil, err
	}

	if *k.Curve != NamedEllipticCurve_PRIME256_V1 {
		return nil, newError("bad Curve")
	}

	x, y := elliptic.Unmarshal(elliptic.P256(), k.EcPublic)
	pk := &ecdsa.PrivateKey{
		D: new(big.Int).SetBytes(k.EcPrivate),
		PublicKey: ecdsa.PublicKey{
			Curve: elliptic.P256(),
			X:     x,
			Y:     y,
		},
	}

	return &Signer{pk}, nil
}

作者:netkicor    项目:go-partner-api-clien   
func TestProcessRequestUserKey(t *testing.T) {
	server, client := setupHttp(200, "application/json", `{"success":true,"message":"my message"}`)
	defer server.Close()

	// Create Test Keys
	userKey := new(ecdsa.PrivateKey)
	userKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	partnerKey := new(ecdsa.PrivateKey)
	partnerKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	// Sign User's Public Key (SHA1 Hash)  with Partner's Key
	userPubkey, _ := x509.MarshalPKIXPublicKey(&userKey.PublicKey)
	hash := sha1.New().Sum(userPubkey)
	r, s, _ := ecdsa.Sign(rand.Reader, partnerKey, hash)
	sigToMarshal := &ecdsaSignature{R: r, S: s}
	keySig, _ := asn1.Marshal(sigToMarshal)

	userKeyPartner := &NetkiPartner{UserKey: userKey, KeySigningKey: &partnerKey.PublicKey, KeySignature: keySig}

	requester := &NetkiRequester{HTTPClient: client}
	result, err := requester.ProcessRequest(userKeyPartner, "http://domain.com/uri", "GET", "")

	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, result)
}

作者:hyperledge    项目:fabri   
func TestKeyGenECDSAOpts(t *testing.T) {
	// Curve P256
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA P256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA P256 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA P256 key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA P256 key. Key should be asymmetric")
	}

	ecdsaKey := k.(*ecdsaPrivateKey).privKey
	if !elliptic.P256().IsOnCurve(ecdsaKey.X, ecdsaKey.Y) {
		t.Fatal("P256 generated key in invalid. The public key must be on the P256 curve.")
	}
	if elliptic.P256() != ecdsaKey.Curve {
		t.Fatal("P256 generated key in invalid. The curve must be P256.")
	}
	if ecdsaKey.D.Cmp(big.NewInt(0)) == 0 {
		t.Fatal("P256 generated key in invalid. Private key must be different from 0.")
	}

	// Curve P384
	k, err = currentBCCSP.KeyGen(&bccsp.ECDSAP384KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA P384 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA P384 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA P384 key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA P384 key. Key should be asymmetric")
	}

	ecdsaKey = k.(*ecdsaPrivateKey).privKey
	if !elliptic.P384().IsOnCurve(ecdsaKey.X, ecdsaKey.Y) {
		t.Fatal("P256 generated key in invalid. The public key must be on the P384 curve.")
	}
	if elliptic.P384() != ecdsaKey.Curve {
		t.Fatal("P256 generated key in invalid. The curve must be P384.")
	}
	if ecdsaKey.D.Cmp(big.NewInt(0)) == 0 {
		t.Fatal("P256 generated key in invalid. Private key must be different from 0.")
	}

}

作者:jmptrade    项目:gocrypt   
func TestGenerateKey(t *testing.T) {
	var err error

	alicePriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bobPriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

作者:tmroede    项目:cloudprox   
func unmarshalECDSASHAVerifyingKeyV1(v *ECDSA_SHA_VerifyingKeyV1) (*ecdsa.PublicKey, error) {
	if *v.Curve != NamedEllipticCurve_PRIME256_V1 {
		return nil, newError("bad curve")
	}

	x, y := elliptic.Unmarshal(elliptic.P256(), v.EcPublic)
	pk := &ecdsa.PublicKey{
		Curve: elliptic.P256(),
		X:     x,
		Y:     y,
	}
	return pk, nil
}

作者:jfrazell    项目:boulde   
func TestLogCache(t *testing.T) {
	cache := logCache{
		logs: make(map[string]*Log),
	}

	// Adding a log with an invalid base64 public key should error
	_, err := cache.AddLog("www.test.com", "1234")
	test.AssertError(t, err, "AddLog() with invalid base64 pk didn't error")

	// Adding a log with an invalid URI should error
	_, err = cache.AddLog(":", "")
	test.AssertError(t, err, "AddLog() with an invalid log URI didn't error")

	// Create one keypair & base 64 public key
	k1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k1")
	der1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey)
	test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der1) failed")
	k1b64 := base64.StdEncoding.EncodeToString(der1)

	// Create a second keypair & base64 public key
	k2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k2")
	der2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey)
	test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der2) failed")
	k2b64 := base64.StdEncoding.EncodeToString(der2)

	// Adding the first log should not produce an error
	l1, err := cache.AddLog("http://log.one.example.com", k1b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for log 1")
	test.AssertEquals(t, cache.Len(), 1)
	test.AssertEquals(t, l1.uri, "http://log.one.example.com")
	test.AssertEquals(t, l1.logID, k1b64)

	// Adding it again should not produce any errors, or increase the Len()
	l1, err = cache.AddLog("http://log.one.example.com", k1b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for second add of log 1")
	test.AssertEquals(t, cache.Len(), 1)
	test.AssertEquals(t, l1.uri, "http://log.one.example.com")
	test.AssertEquals(t, l1.logID, k1b64)

	// Adding a second log should not error and should increase the Len()
	l2, err := cache.AddLog("http://log.two.example.com", k2b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for log 2")
	test.AssertEquals(t, cache.Len(), 2)
	test.AssertEquals(t, l2.uri, "http://log.two.example.com")
	test.AssertEquals(t, l2.logID, k2b64)
}

作者:admpu    项目:u2   
func parseRegistration(buf []byte) (*Registration, []byte, error) {
	if len(buf) < 1+65+1+1+1 {
		return nil, nil, errors.New("u2f: data is too short")
	}

	var r Registration
	r.Raw = buf

	if buf[0] != 0x05 {
		return nil, nil, errors.New("u2f: invalid reserved byte")
	}
	buf = buf[1:]

	x, y := elliptic.Unmarshal(elliptic.P256(), buf[:65])
	if x == nil {
		return nil, nil, errors.New("u2f: invalid public key")
	}
	r.PubKey.Curve = elliptic.P256()
	r.PubKey.X = x
	r.PubKey.Y = y
	buf = buf[65:]

	khLen := int(buf[0])
	buf = buf[1:]
	if len(buf) < khLen {
		return nil, nil, errors.New("u2f: invalid key handle")
	}
	r.KeyHandle = buf[:khLen]
	buf = buf[khLen:]

	// The length of the x509 cert isn't specified so it has to be inferred
	// by parsing. We can't use x509.ParseCertificate yet because it returns
	// an error if there are any trailing bytes. So parse raw asn1 as a
	// workaround to get the length.
	sig, err := asn1.Unmarshal(buf, &asn1.RawValue{})
	if err != nil {
		return nil, nil, err
	}

	buf = buf[:len(buf)-len(sig)]
	cert, err := x509.ParseCertificate(buf)
	if err != nil {
		return nil, nil, err
	}
	r.AttestationCert = cert

	return &r, sig, nil
}

作者:CometKi    项目:platfor   
func TestJWKValid(t *testing.T) {
	bigInt := big.NewInt(0)
	eccPub := ecdsa.PublicKey{elliptic.P256(), bigInt, bigInt}
	rsaPub := rsa.PublicKey{bigInt, 1}
	cases := []struct {
		key              interface{}
		expectedValidity bool
	}{
		{nil, false},
		{&ecdsa.PublicKey{}, false},
		{&eccPub, true},
		{&ecdsa.PrivateKey{}, false},
		{&ecdsa.PrivateKey{eccPub, bigInt}, true},
		{&rsa.PublicKey{}, false},
		{&rsaPub, true},
		{&rsa.PrivateKey{}, false},
		{&rsa.PrivateKey{rsaPub, bigInt, []*big.Int{bigInt, bigInt}, rsa.PrecomputedValues{}}, true},
	}

	for _, tc := range cases {
		k := &JsonWebKey{Key: tc.key}
		if valid := k.Valid(); valid != tc.expectedValidity {
			t.Errorf("expected Valid to return %t, got %t", tc.expectedValidity, valid)
		}
	}
}

作者:willbittne    项目:moj   
// newPrincipalKey generates an ECDSA (public, private) key pair.
func newPrincipalKey() (publicKey, *ecdsa.PrivateKey, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}
	return newECDSAPublicKey(&priv.PublicKey), priv, nil
}

作者:JoeHor    项目:boulde   
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *KeyRequest) Generate() (interface{}, error) {
	log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo, kr.Size)
	switch kr.Algo {
	case "rsa":
		if kr.Size < 2048 {
			return nil, errors.New("RSA key is too weak")
		}
		return rsa.GenerateKey(rand.Reader, kr.Size)
	case "ecdsa":
		var curve elliptic.Curve
		switch kr.Size {
		case curveP256:
			curve = elliptic.P256()
		case curveP384:
			curve = elliptic.P384()
		case curveP521:
			curve = elliptic.P521()
		default:
			return nil, errors.New("invalid curve")
		}
		return ecdsa.GenerateKey(curve, rand.Reader)
	default:
		return nil, errors.New("invalid algorithm")
	}
}

作者:wallra    项目:dn   
// publicKeyCurve returns the Curve public key from the DNSKEY record.
func (k *RR_DNSKEY) publicKeyCurve() *ecdsa.PublicKey {
	keybuf, err := packBase64([]byte(k.PublicKey))
	if err != nil {
		return nil
	}
	pubkey := new(ecdsa.PublicKey)
	switch k.Algorithm {
	case ECDSAP256SHA256:
		pubkey.Curve = elliptic.P256()
		if len(keybuf) != 64 {
			// wrongly encoded key
			return nil
		}
	case ECDSAP384SHA384:
		pubkey.Curve = elliptic.P384()
		if len(keybuf) != 96 {
			// Wrongly encoded key
			return nil
		}
	}
	pubkey.X = big.NewInt(0)
	pubkey.X.SetBytes(keybuf[:len(keybuf)/2])
	pubkey.Y = big.NewInt(0)
	pubkey.Y.SetBytes(keybuf[len(keybuf)/2:])
	return pubkey
}

作者:bbandi    项目:cfss   
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
	log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
	switch kr.Algo() {
	case "rsa":
		if kr.Size() < 2048 {
			return nil, errors.New("RSA key is too weak")
		}
		if kr.Size() > 8192 {
			return nil, errors.New("RSA key size too large")
		}
		return rsa.GenerateKey(rand.Reader, kr.Size())
	case "ecdsa":
		var curve elliptic.Curve
		switch kr.Size() {
		case curveP256:
			curve = elliptic.P256()
		case curveP384:
			curve = elliptic.P384()
		case curveP521:
			curve = elliptic.P521()
		default:
			return nil, errors.New("invalid curve")
		}
		return ecdsa.GenerateKey(curve, rand.Reader)
	default:
		return nil, errors.New("invalid algorithm")
	}
}

作者:boardyu    项目:go-jos   
func TestMarshalUnmarshalInvalid(t *testing.T) {
	keys := []interface{}{
		// Empty keys
		&rsa.PrivateKey{},
		&ecdsa.PrivateKey{},
		// Invalid keys
		&ecdsa.PrivateKey{
			PublicKey: ecdsa.PublicKey{
				// Missing values in pub key
				Curve: elliptic.P256(),
			},
		},
		&ecdsa.PrivateKey{
			PublicKey: ecdsa.PublicKey{
				// Invalid curve
				Curve: nil,
				X:     ecTestKey256.X,
				Y:     ecTestKey256.Y,
			},
		},
		&ecdsa.PrivateKey{
			// Valid pub key, but missing priv key values
			PublicKey: ecTestKey256.PublicKey,
		},
		nil,
	}

	for i, key := range keys {
		jwk := JsonWebKey{Key: key}
		_, err := jwk.MarshalJSON()
		if err == nil {
			t.Error("managed to serialize invalid key", i)
		}
	}
}

作者:ericchian    项目:de   
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
}

作者:andres-erbse    项目:tlstestuti   
// CA returns a new CA certificate, a pool containing that certificate, and the
// corresponding private key.
func CA(t *testing.T, rnd io.Reader) (*x509.Certificate, *x509.CertPool, *ecdsa.PrivateKey) {
	if rnd == nil {
		rnd = rand.Reader
	}
	var err error
	caPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), rnd)
	if err != nil {
		t.Fatal(err)
	}
	caCertTemplate := &x509.Certificate{
		Subject:               pkix.Name{CommonName: "testingCA"},
		SerialNumber:          newSerial(t, rnd),
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:       true,
		MaxPathLen: 4,
	}
	caCertDER, err := x509.CreateCertificate(rnd, caCertTemplate, caCertTemplate, &caPrivKey.PublicKey, caPrivKey)
	if err != nil {
		t.Fatal(err)
	}
	caCert, err := x509.ParseCertificate(caCertDER)
	if err != nil {
		t.Fatal(err)
	}

	caPool := x509.NewCertPool()
	caPool.AddCert(caCert)
	return caCert, caPool, caPrivKey
}

作者:Jyggafe    项目:dron   
func init() {
	raw256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	ecdsaKey, _ = NewSignerFromKey(raw256)

	raw384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	ecdsa384Key, _ = NewSignerFromKey(raw384)

	raw521, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	ecdsa521Key, _ = NewSignerFromKey(raw521)

	// Create a cert and sign it for use in tests.
	testCert := &OpenSSHCertV01{
		Nonce:           []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
		Key:             ecdsaKey.PublicKey(),
		ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage
		ValidAfter:      0,                              // unix epoch
		ValidBefore:     maxUint64,                      // The end of currently representable time.
		Reserved:        []byte{},                       // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
		SignatureKey:    rsaKey.PublicKey(),
	}
	sigBytes, _ := rsaKey.Sign(rand.Reader, testCert.BytesForSigning())
	testCert.Signature = &signature{
		Format: testCert.SignatureKey.PublicKeyAlgo(),
		Blob:   sigBytes,
	}
	testCertKey = &testSigner{
		Signer: ecdsaKey,
		pub:    testCert,
	}
}


问题


面经


文章

微信
公众号

扫码关注公众号