func TestKeyLength(t *testing.T) { expNil := 0 recNil := KeyLength(nil) if expNil != recNil { t.Fatal("KeyLength on nil did not return 0") } expNonsense := 0 inNonsense := "string?" outNonsense := KeyLength(inNonsense) if expNonsense != outNonsense { t.Fatal("KeyLength malfunctioning on nonsense input") } //test the ecdsa branch ecdsaPriv, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) ecdsaIn, _ := ecdsaPriv.Public().(*ecdsa.PublicKey) expEcdsa := ecdsaIn.Curve.Params().BitSize outEcdsa := KeyLength(ecdsaIn) if expEcdsa != outEcdsa { t.Fatal("KeyLength malfunctioning on ecdsa input") } //test the rsa branch rsaPriv, _ := rsa.GenerateKey(rand.Reader, 256) rsaIn, _ := rsaPriv.Public().(*rsa.PublicKey) expRsa := rsaIn.N.BitLen() outRsa := KeyLength(rsaIn) if expRsa != outRsa { t.Fatal("KeyLength malfunctioning on rsa input") } }
func TestRoundTripPkcs8Ecdsa(t *testing.T) { privateKey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("failed to generate a private key: %s", err) } bytes, err := marshalPKCS8PrivateKey(privateKey) if err != nil { t.Fatalf("failed to marshal private key: %s", err) } key, err := x509.ParsePKCS8PrivateKey(bytes) if err != nil { t.Fatalf("failed to parse private key: %s", err) } actualPrivateKey, ok := key.(*ecdsa.PrivateKey) if !ok { t.Fatalf("expected key to be of type *ecdsa.PrivateKey, but actual was %T", key) } // sanity check, not exhaustive if actualPrivateKey.D.Cmp(privateKey.D) != 0 { t.Errorf("private key's D did not round trip") } if actualPrivateKey.X.Cmp(privateKey.X) != 0 { t.Errorf("private key's X did not round trip") } if actualPrivateKey.Y.Cmp(privateKey.Y) != 0 { t.Errorf("private key's Y did not round trip") } if actualPrivateKey.Curve.Params().B.Cmp(privateKey.Curve.Params().B) != 0 { t.Errorf("private key's Curve.B did not round trip") } }
func TestKeyGeneration(t *testing.T) { testKeyGeneration(t, elliptic.P224(), "p224") if testing.Short() { return } testKeyGeneration(t, gost3410a, "gost3410a") }
func createCertificateAndKeys() { // http://golang.org/pkg/crypto/x509/#Certificate privatekey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { fmt.Println(err) } publickey := &privatekey.PublicKey certTemplate := getCertificateTemplate() cert, err := x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, publickey, privatekey) if err != nil { fmt.Println(err) } writePemCertificate(cert, "btcd/root/.btcd/rpc.cert") writePemPrivateKey(privatekey, "btcd/root/.btcd/rpc.key") writePemCertificate(cert, "btcwallet/root/.btcd/rpc.cert") writePemCertificate(cert, "btcwallet/root/.btcwallet/btcd.cert") writePemCertificate(cert, "btcwallet/root/.btcwallet/rpcw.cert") writePemPrivateKey(privatekey, "btcwallet/root/.btcwallet/rpcw.key") }
// GenerateKeyPair generates a private/public key pair, // keys are returned as hex-encoded strings func GenerateKeyPair() (private_key_hex, public_key_hex string) { // generate keys private_key, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { panic(err) } // marshal private key private_key_bytes, err := x509.MarshalECPrivateKey(private_key) if err != nil { panic(err) } // marshal public key public_key_bytes, err := x509.MarshalPKIXPublicKey(&private_key.PublicKey) if err != nil { panic(err) } // hex encode and return result private_key_hex = hex.EncodeToString(private_key_bytes) public_key_hex = hex.EncodeToString(public_key_bytes) return private_key_hex, public_key_hex }
func main() { u := must(url.Parse("http://SUCCESS")) b, x, y := must(elliptic.GenerateKey(elliptic.P224(), ConstWriter(0))) if must(url.Parse("http://example.com/a/b")).IsAbs() { fmt.Println(u.Host) } }
func TestECDSAVerifierOtherCurves(t *testing.T) { curves := []elliptic.Curve{elliptic.P224(), elliptic.P256(), elliptic.P384(), elliptic.P521()} for _, curve := range curves { ecdsaPrivKey, err := ecdsa.GenerateKey(curve, rand.Reader) // Get a DER-encoded representation of the PublicKey ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey) assert.NoError(t, err, "failed to marshal public key") // Get a DER-encoded representation of the PrivateKey ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey) assert.NoError(t, err, "failed to marshal private key") testECDSAKey := data.NewPrivateKey(data.ECDSAKey, ecdsaPubBytes, ecdsaPrivKeyBytes) // Sign some data using ECDSA message := []byte("test data for signing") hashed := sha256.Sum256(message) signedData, err := ecdsaSign(testECDSAKey, hashed[:]) assert.NoError(t, err) // Create and call Verify on the verifier ecdsaVerifier := ECDSAVerifier{} err = ecdsaVerifier.Verify(testECDSAKey, signedData, message) assert.NoError(t, err, "expecting success but got error while verifying data using ECDSA") // Make sure an invalid signature fails verification signedData[0]++ err = ecdsaVerifier.Verify(testECDSAKey, signedData, message) assert.Error(t, err, "expecting error but got success while verifying data using ECDSA") } }
func TestNullParametersPkcs8Ecdsa(t *testing.T) { privateKey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("failed to generate a private key: %s", err) } checkNullParameter(t, privateKey) }
func BenchmarkRawCreateP224(b *testing.B) { data := "foo" k, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) b.ResetTimer() for i := 0; i < b.N; i++ { ecdsa.Sign(rand.Reader, k, []byte(data)) } }
func TestSignAndVerify(t *testing.T) { testSignAndVerify(t, elliptic.P224(), "p224") if testing.Short() { return } testSignAndVerify(t, elliptic.P256(), "p256") testSignAndVerify(t, elliptic.P384(), "p384") testSignAndVerify(t, elliptic.P521(), "p521") }
func TestKeyGeneration(t *testing.T) { testKeyGeneration(t, elliptic.P224(), "p224") if testing.Short() { return } testKeyGeneration(t, elliptic.P256(), "p256") testKeyGeneration(t, elliptic.P384(), "p384") testKeyGeneration(t, elliptic.P521(), "p521") }
func TestINDCCA(t *testing.T) { testINDCCA(t, elliptic.P224(), "p224") if testing.Short() { return } testINDCCA(t, elliptic.P256(), "p256") testINDCCA(t, elliptic.P384(), "p384") testINDCCA(t, elliptic.P521(), "p521") }
func TestNewSignatureVerifierFailsWithBadKeyParametersForEC(t *testing.T) { k, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("Failed to generate ECDSA key on P224: %v", err) } if _, err := NewSignatureVerifier(k); err == nil { t.Fatal("Incorrectly created new SignatureVerifier with EC P224 key.") } }
func TestWillAllowNonCompliantECKeyWithOverride(t *testing.T) { *allowVerificationWithNonCompliantKeys = true k, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("Failed to generate EC key on P224: %v", err) } if _, err := NewSignatureVerifier(k.Public()); err != nil { t.Fatalf("Incorrectly disallowed P224 EC key with override set: %v", err) } }
func BenchmarkRawVerifyP224(b *testing.B) { data := "foo" k, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) R, S, _ := ecdsa.Sign(rand.Reader, k, []byte(data)) pk := &k.PublicKey b.ResetTimer() for i := 0; i < b.N; i++ { ecdsa.Verify(pk, []byte(data), R, S) } }
func TestAlgoNameNotSupported(t *testing.T) { notSupported := []interface{}{ &ecdsa.PublicKey{Curve: elliptic.P224()}, &OpenSSHCertV01{Key: &ecdsa.PublicKey{Curve: elliptic.P224()}}, } panicTest := func(key interface{}) (algo string, err error) { defer func() { if r := recover(); r != nil { err = errors.New(r.(string)) } }() algo = algoName(key) return } for _, unsupportedKey := range notSupported { if algo, err := panicTest(unsupportedKey); err == nil { t.Errorf("Expected a panic, Got: %s (for type %T)", algo, unsupportedKey) } } }
func curveToRaw(curve elliptic.Curve) (rv asn1.RawValue, ok bool) { switch curve { case elliptic.P224(), elliptic.P256(), elliptic.P384(), elliptic.P521(): raw := rawCurve(curve) return asn1.RawValue{ Tag: 30, Bytes: raw[2:], FullBytes: raw, }, true default: return rv, false } }
func GenerateNewKeypair() *Keypair { pk, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) b := bigJoin(KEY_SIZE, pk.PublicKey.X, pk.PublicKey.Y) public := base58.EncodeBig([]byte{}, b) private := base58.EncodeBig([]byte{}, pk.D) kp := Keypair{Public: public, Private: private} return &kp }
// OidFromNamedCurve returns the OID used to specify the use of the given // elliptic curve. func OidFromNamedCurve(curve elliptic.Curve) asn1.ObjectIdentifier { switch curve { case elliptic.P224(): return OidNamedCurveP224 case elliptic.P256(): return OidNamedCurveP256 case elliptic.P384(): return OidNamedCurveP384 case elliptic.P521(): return OidNamedCurveP521 } return nil }
func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { switch curve { case elliptic.P224(): return oidNamedCurveP224, true case elliptic.P256(): return oidNamedCurveP256, true case elliptic.P384(): return oidNamedCurveP384, true case elliptic.P521(): return oidNamedCurveP521, true } return nil, false }
func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { switch { case oid.Equal(oidNamedCurveP224): return elliptic.P224() case oid.Equal(oidNamedCurveP256): return elliptic.P256() case oid.Equal(oidNamedCurveP384): return elliptic.P384() case oid.Equal(oidNamedCurveP521): return elliptic.P521() } return nil }
func namedCurveFromOID(curve secgNamedCurve) elliptic.Curve { switch { case curve.Equal(secgNamedCurveP224): return elliptic.P224() case curve.Equal(secgNamedCurveP256): return elliptic.P256() case curve.Equal(secgNamedCurveP384): return elliptic.P384() case curve.Equal(secgNamedCurveP521): return elliptic.P521() } return nil }
func TestUnsupportedCurves(t *testing.T) { raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("GenerateKey: %v", err) } if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P256") { t.Fatalf("NewPrivateKey should not succeed with P224, got: %v", err) } if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P256") { t.Fatalf("NewPublicKey should not succeed with P224, got: %v", err) } }
// Generates an ephemeral public key and returns a function that will compute // the shared secret key. Used in the identify module. // // Focuses only on ECDH now, but can be made more general in the future. func GenerateEKeyPair(curveName string) ([]byte, GenSharedKey, error) { var curve elliptic.Curve switch curveName { case "P-224": curve = elliptic.P224() case "P-256": curve = elliptic.P256() case "P-384": curve = elliptic.P384() case "P-521": curve = elliptic.P521() } priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader) if err != nil { return nil, nil, err } var pubKey bytes.Buffer pubKey.Write(x.Bytes()) pubKey.Write(y.Bytes()) done := func(theirPub []byte) ([]byte, error) { // Verify and unpack node's public key. curveSize := curve.Params().BitSize if len(theirPub) != (curveSize / 4) { return nil, errors.New("Malformed public key.") } bound := (curveSize / 8) x := big.NewInt(0) y := big.NewInt(0) x.SetBytes(theirPub[0:bound]) y.SetBytes(theirPub[bound : bound*2]) if !curve.IsOnCurve(x, y) { return nil, errors.New("Invalid public key.") } // Generate shared secret. secret, _ := curve.ScalarMult(x, y, priv) return secret.Bytes(), nil } return pubKey.Bytes(), done, nil }
func SignatureVerify(publicKey, sig, hash []byte) bool { b, _ := base58.DecodeToBig(publicKey) publ := splitBig(b, 2) x, y := publ[0], publ[1] b, _ = base58.DecodeToBig(sig) sigg := splitBig(b, 2) r, s := sigg[0], sigg[1] pub := ecdsa.PublicKey{elliptic.P224(), x, y} return ecdsa.Verify(&pub, hash, r, s) }
func oidFromNamedCurve(curve elliptic.Curve) (secgNamedCurve, bool) { switch curve { case elliptic.P224(): return secgNamedCurveP224, true case elliptic.P256(): return secgNamedCurveP256, true case elliptic.P384(): return secgNamedCurveP384, true case elliptic.P521(): return secgNamedCurveP521, true } return nil, false }
func curve_id(c elliptic.Curve) string { switch c { case elliptic.P224(): return "P224" case elliptic.P256(): return "P256" case elliptic.P384(): return "P384" case elliptic.P521(): return "P521" default: return "" } }
func get_curve(id string) elliptic.Curve { switch id { case "P224": return elliptic.P224() case "P256": return elliptic.P256() case "P384": return elliptic.P384() case "P521": return elliptic.P521() default: return nil } }
func rawCurve(curve elliptic.Curve) []byte { switch curve { case elliptic.P224(): return rawCurveP224 case elliptic.P256(): return rawCurveP256 case elliptic.P384(): return rawCurveP384 case elliptic.P521(): return rawCurveP521 default: return nil } }
// NewCertificateRequest generates a PEM-encoded CSR using the supplied private key, subject, and SANs. // privateKey must be a *ecdsa.PrivateKey or *rsa.PrivateKey. func NewCertificateRequest(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) { var sigType x509.SignatureAlgorithm switch privateKey := privateKey.(type) { case *ecdsa.PrivateKey: switch privateKey.Curve { case elliptic.P224(), elliptic.P256(): sigType = x509.ECDSAWithSHA256 case elliptic.P384(): sigType = x509.ECDSAWithSHA384 case elliptic.P521(): sigType = x509.ECDSAWithSHA512 default: return nil, fmt.Errorf("unknown elliptic curve: %v", privateKey.Curve) } case *rsa.PrivateKey: keySize := privateKey.N.BitLen() switch { case keySize >= 4096: sigType = x509.SHA512WithRSA case keySize >= 3072: sigType = x509.SHA384WithRSA default: sigType = x509.SHA256WithRSA } default: return nil, fmt.Errorf("unsupported key type: %T", privateKey) } template := &x509.CertificateRequest{ Subject: *subject, SignatureAlgorithm: sigType, DNSNames: dnsSANs, IPAddresses: ipSANs, } csr, err = x509.CreateCertificateRequest(cryptorand.Reader, template, privateKey) if err != nil { return nil, err } csrPemBlock := &pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: csr, } return pem.EncodeToMemory(csrPemBlock), nil }