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") } }
func CreatePrivateKey(keyType KeyType, curve Curve, rsaBits *int) (interface{}, error) { switch keyType { case KeyEcdsa: switch curve { case curveDefault: return CreateEcdsaPrivateKey(elliptic.P521()) case CurveP256: return CreateEcdsaPrivateKey(elliptic.P256()) case CurveP384: return CreateEcdsaPrivateKey(elliptic.P384()) case CurveP521: return CreateEcdsaPrivateKey(elliptic.P521()) default: return nil, UnknownCurve } case KeyRSA: bits := 2048 if nil != rsaBits { bits = *rsaBits } if bits < 2048 || bits > 4096 { return nil, InvalidRsaBits } return CreateRsaPrivateKey(bits) default: return nil, UnknownKeyType } }
//PrivteKeyFromBytes makes a private key from a slice of bytes and returns it. func PrivateKeyFromBytes(b []byte) (priv *PrivateKey, err error) { if len(b) < 64 { return nil, fmt.Errorf("Could not parse commit bytes") } D := new(big.Int).SetBytes(b) priv = new(PrivateKey) priv.PublicKey.Curve = elliptic.P521() priv.PublicKey.X, priv.PublicKey.Y = elliptic.P521().ScalarBaseMult(b) priv.D = D return priv, nil }
func loadECDSAPub(in []byte) (*ecdsa.PublicKey, error) { x, y := elliptic.Unmarshal(elliptic.P521(), in) if x == nil { return nil, errors.New("crypto: invalid ECDSA public key") } return &ecdsa.PublicKey{ X: x, Y: y, Curve: elliptic.P521(), }, nil }
func TestSetupKeys(t *testing.T) { var err error alice, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { t.Fatalf("%v", err) } bob, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { t.Fatalf("%v", err) } }
//GetPublicKeyForHkid uses the lookup services to get a public key for an hkid func GetPublicKeyForHkid(hkid objects.HKID) objects.PublicKey { marshaledKey, err := GetBlob(objects.HCID(hkid)) if err != nil { return objects.PublicKey{} } curve := elliptic.P521() x, y := elliptic.Unmarshal(elliptic.P521(), marshaledKey) pubKey := ecdsa.PublicKey{ Curve: curve, //elliptic.Curve X: x, //X *big.Int Y: y} //Y *big.Int return objects.PublicKey(pubKey) }
func generateKey() *ecdsa.PrivateKey { prv, x, y, err := elliptic.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { fmt.Printf("Key generation failed: %v\n", err.Error()) os.Exit(1) } return &ecdsa.PrivateKey{ D: new(big.Int).SetBytes(prv), PublicKey: ecdsa.PublicKey{ Curve: elliptic.P521(), X: x, Y: y, }, } }
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, } }
func generatePriv() (*ecdsa.PrivateKey, error) { priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, err } return priv, nil }
func GenerateSigningTestKey(sigAlg SignatureAlgorithm) (sig, ver interface{}) { switch sigAlg { case RS256, RS384, RS512, PS256, PS384, PS512: sig = rsaTestKey ver = &rsaTestKey.PublicKey case HS256, HS384, HS512: sig, _, _ = randomKeyGenerator{size: 16}.genKey() ver = sig case ES256: key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) sig = key ver = &key.PublicKey case ES384: key, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) sig = key ver = &key.PublicKey case ES512: key, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) sig = key ver = &key.PublicKey default: panic("Must update test case") } return }
func marshalECDSAKey(priv *ecdsa.PrivateKey) (out []byte, err error) { var eckey ecPrivateKey eckey.Version = 1 eckey.PrivateKey = priv.D.Bytes() switch priv.PublicKey.Curve { case elliptic.P256(): eckey.NamedCurveOID = oidNamedCurveP256 case elliptic.P384(): eckey.NamedCurveOID = oidNamedCurveP384 case elliptic.P521(): eckey.NamedCurveOID = oidNamedCurveP521 default: err = ErrInvalidPrivateKey } pkey := elliptic.Marshal(priv.PublicKey.Curve, priv.PublicKey.X, priv.PublicKey.Y) if pkey == nil { err = ErrInvalidPrivateKey return } eckey.PublicKey = asn1.BitString{ BitLength: len(pkey) * 8, Bytes: pkey, } out, err = asn1.Marshal(eckey) return }
func TestECDSAVerifierOtherCurves(t *testing.T) { curves := []elliptic.Curve{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") testECDSAPubKey := data.NewECDSAPublicKey(ecdsaPubBytes) testECDSAKey, err := data.NewECDSAPrivateKey(testECDSAPubKey, ecdsaPrivKeyBytes) assert.NoError(t, err, "failed to read private key") // 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") } }
// Sign creates a JWT using the signing key. func (k Keys) Sign(payload []byte) (jws string, err error) { if k.SigningKey == nil { return "", fmt.Errorf("no key to sign payload with") } signingKey := jose.SigningKey{Key: k.SigningKey} switch key := k.SigningKey.Key.(type) { case *rsa.PrivateKey: // TODO(ericchiang): Allow different cryptographic hashes. signingKey.Algorithm = jose.RS256 case *ecdsa.PrivateKey: switch key.Params() { case elliptic.P256().Params(): signingKey.Algorithm = jose.ES256 case elliptic.P384().Params(): signingKey.Algorithm = jose.ES384 case elliptic.P521().Params(): signingKey.Algorithm = jose.ES512 default: return "", errors.New("unsupported ecdsa curve") } } signer, err := jose.NewSigner(signingKey, &jose.SignerOptions{}) if err != nil { return "", fmt.Errorf("new signier: %v", err) } signature, err := signer.Sign(payload) if err != nil { return "", fmt.Errorf("signing payload: %v", err) } return signature.CompactSerialize() }
// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { var identifier []byte var ok bool if identifier, in, ok = parseString(in); !ok { return nil, nil, errShortRead } key := new(ecdsa.PublicKey) switch string(identifier) { case "nistp256": key.Curve = elliptic.P256() case "nistp384": key.Curve = elliptic.P384() case "nistp521": key.Curve = elliptic.P521() default: return nil, nil, errors.New("ssh: unsupported curve") } var keyBytes []byte if keyBytes, in, ok = parseString(in); !ok { return nil, nil, errShortRead } key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes) if key.X == nil || key.Y == nil { return nil, nil, errors.New("ssh: invalid curve point") } return (*ecdsaPublicKey)(key), in, nil }
// DefaultSigAlgo returns an appropriate X.509 signature algorithm given // the CA's private key. func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm { pub := priv.Public() switch pub := pub.(type) { case *rsa.PublicKey: keySize := pub.N.BitLen() switch { case keySize >= 4096: return x509.SHA512WithRSA case keySize >= 3072: return x509.SHA384WithRSA case keySize >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case *ecdsa.PublicKey: switch pub.Curve { case elliptic.P256(): return x509.ECDSAWithSHA256 case elliptic.P384(): return x509.ECDSAWithSHA384 case elliptic.P521(): return x509.ECDSAWithSHA512 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
// 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") } }
func GenerateEmptyConfig() (*tls.Config, error) { priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, err } number, err := rand.Int(rand.Reader, big.NewInt(0).Lsh(big.NewInt(1), 128)) if err != nil { return nil, err } cert := &x509.Certificate{ SerialNumber: number, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour * 24), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, BasicConstraintsValid: true, } certbytes, err := x509.CreateCertificate(rand.Reader, cert, cert, &priv.PublicKey, priv) if err != nil { return nil, err } ct := tls.Certificate{[][]byte{certbytes}, priv, nil, cert} c := &tls.Config{InsecureSkipVerify: true} c.Certificates = append(c.Certificates, ct) c.NextProtos = []string{Proto} return c, nil }
func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoECDSA, PublicKey: pub, ec: new(ecdsaKey), } switch pub.Curve { case elliptic.P256(): pk.ec.oid = oidCurveP256 case elliptic.P384(): pk.ec.oid = oidCurveP384 case elliptic.P521(): pk.ec.oid = oidCurveP521 default: panic("unknown elliptic curve") } pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes)) pk.setFingerPrintAndKeyId() return pk }
// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { var w struct { Curve string KeyBytes []byte Rest []byte `ssh:"rest"` } if err := Unmarshal(in, &w); err != nil { return nil, nil, err } key := new(ecdsa.PublicKey) switch w.Curve { case "nistp256": key.Curve = elliptic.P256() case "nistp384": key.Curve = elliptic.P384() case "nistp521": key.Curve = elliptic.P521() default: return nil, nil, errors.New("ssh: unsupported curve") } key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) if key.X == nil || key.Y == nil { return nil, nil, errors.New("ssh: invalid curve point") } return (*ecdsaPublicKey)(key), w.Rest, nil }
// DefaultSigAlgo returns an appropriate X.509 signature algorithm given the // CA's private key. func DefaultSigAlgo(priv interface{}) x509.SignatureAlgorithm { switch priv := priv.(type) { case *rsa.PrivateKey: keySize := priv.N.BitLen() switch { case keySize >= 4096: return x509.SHA512WithRSA case keySize >= 3072: return x509.SHA384WithRSA case keySize >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case *ecdsa.PrivateKey: switch priv.Curve { case elliptic.P256(): return x509.ECDSAWithSHA256 case elliptic.P384(): return x509.ECDSAWithSHA384 case elliptic.P521(): return x509.ECDSAWithSHA512 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out *ecdsa.PublicKey, rest []byte, ok bool) { var identifier []byte if identifier, in, ok = parseString(in); !ok { return } key := new(ecdsa.PublicKey) switch string(identifier) { case "nistp256": key.Curve = elliptic.P256() case "nistp384": key.Curve = elliptic.P384() case "nistp521": key.Curve = elliptic.P521() default: ok = false return } var keyBytes []byte if keyBytes, in, ok = parseString(in); !ok { return } key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes) if key.X == nil || key.Y == nil { ok = false return } return key, in, ok }
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 }
func init() { // This is the group called diffie-hellman-group1-sha1 in RFC // 4253 and Oakley Group 2 in RFC 2409. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, } // This is the group called diffie-hellman-group14-sha1 in RFC // 4253 and Oakley Group 14 in RFC 3526. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, } kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} kexAlgoMap[kexAlgoDHGEXSHA1] = &dhGEXSHA1{} }
// 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") } }
func EncodeKey(k *ecdsa.PublicKey) *EncodedKey { if k.Curve != elliptic.P521() { panic("Incorrect curve in use") } return &EncodedKey{"ecdsa:P521", k.X, k.Y} }
// GenerateKeys returns a new key pair, with the private and public key // encoded in PEM format. func GenerateKeys() (privKey []byte, pubKey []byte, err error) { // Generate a new key pair key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, nil, err } // Marshal the private key bs, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, nil, err } // Encode it in PEM format privKey = pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: bs, }) // Marshal the public key bs, err = x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, nil, err } // Encode it in PEM format pubKey = pem.EncodeToMemory(&pem.Block{ Type: "EC PUBLIC KEY", Bytes: bs, }) return }
// keyAlgoUbiquity compute the ubiquity of the cert's public key algorithm // RSA, DSA>ECDSA>Unknown func keyAlgoUbiquity(cert *x509.Certificate) KeyAlgoUbiquity { switch cert.PublicKeyAlgorithm { case x509.ECDSA: switch cert.PublicKey.(*ecdsa.PublicKey).Curve { case elliptic.P256(): return ECDSA256Ubiquity case elliptic.P384(): return ECDSA384Ubiquity case elliptic.P521(): return ECDSA521Ubiquity default: return UnknownAlgoUbiquity } case x509.RSA: if cert.PublicKey.(*rsa.PublicKey).N.BitLen() >= 1024 { return RSAUbiquity } else { return UnknownAlgoUbiquity } case x509.DSA: return DSAUbiquity default: return UnknownAlgoUbiquity } }
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") } return &ecdsa.PrivateKey{ PublicKey: ecdsa.PublicKey{ Curve: curve, X: key.X.bigInt(), Y: key.Y.bigInt(), }, D: key.D.bigInt(), }, nil }
// Compute the priority of different key algorithm based performance and security // ECDSA>RSA>DSA>Unknown func keyAlgoPriority(cert *x509.Certificate) int { switch cert.PublicKeyAlgorithm { case x509.ECDSA: switch cert.PublicKey.(*ecdsa.PublicKey).Curve { case elliptic.P256(): return 100 case elliptic.P384(): return 120 case elliptic.P521(): return 140 default: return 100 } case x509.RSA: switch cert.PublicKey.(*rsa.PublicKey).N.BitLen() { case 4096: return 70 case 3072: return 50 case 2048: return 30 // key size <= 1024 are discouraged. default: return 0 } // we do not want to bundle a DSA cert. case x509.DSA: return 0 default: return 0 } }
func main() { c := elliptic.P521() sec, _ := ecdsa.GenerateKey(c, rand.Reader) pub := &sec.PublicKey log.Print("pub", pub) log.Print("sec", sec) pempub := exportPublicKeytoPEM(pub) pemsec := exportPrivateKeytoEncryptedPEM(sec, []byte("asdfgh")) log.Print("pempub", pempub) log.Print("pemsec", pemsec) pub = importPublicKeyfromPEM(pempub) //sec = importPrivateKeyfromPEM(pemsec) sec = importPrivateKeyfromEncryptedPEM(pemsec, []byte("asdfgh")) log.Print("pub", pub) log.Print("sec", sec) t := sha1.New() io.WriteString(t, "data") // when msg is a string //t.Write([]byte("data")) // when msg is []bye sum1 := t.Sum(nil)[:] r, s, _ := ecdsa.Sign(rand.Reader, sec, sum1) log.Printf("r=%d\ts=%d", r, s) b := ecdsa.Verify(pub, sum1, r, s) log.Printf("b=%v", b) b = ecdsa.Verify(pub, sum1, s, r) log.Printf("b=%v", b) }