Esempio n. 1
0
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.")
	}

}
Esempio n. 2
0
func (ca *CA) createCAKeyPair(name string) *ecdsa.PrivateKey {
	Trace.Println("Creating CA key pair.")

	curve := elliptic.P384()

	priv, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err == nil {
		raw, _ := x509.MarshalECPrivateKey(priv)
		cooked := pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PRIVATE KEY",
				Bytes: raw,
			})
		err := ioutil.WriteFile(ca.path+"/"+name+".priv", cooked, 0644)
		if err != nil {
			Panic.Panicln(err)
		}

		raw, _ = x509.MarshalPKIXPublicKey(&priv.PublicKey)
		cooked = pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PUBLIC KEY",
				Bytes: raw,
			})
		err = ioutil.WriteFile(ca.path+"/"+name+".pub", cooked, 0644)
		if err != nil {
			Panic.Panicln(err)
		}
	}
	if err != nil {
		Panic.Panicln(err)
	}

	return priv
}
Esempio n. 3
0
File: kex.go Progetto: breml/crypto
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{}
}
Esempio n. 4
0
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
}
Esempio n. 5
0
// 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
}
Esempio n. 6
0
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")
	}
}
Esempio n. 7
0
File: server.go Progetto: logan/heim
func (ctrl *Controller) AddHostKeyFromCluster(host string) error {
	generate := func() (string, error) {
		// Generate an ECDSA key.
		key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
		if err != nil {
			return "", err
		}
		derBytes, err := x509.MarshalECPrivateKey(key)
		if err != nil {
			return "", err
		}
		w := &bytes.Buffer{}
		if err := pem.Encode(w, &pem.Block{Type: "EC PRIVATE KEY", Bytes: derBytes}); err != nil {
			return "", err
		}
		return w.String(), nil
	}
	pemString, err := ctrl.cluster.GetValueWithDefault(fmt.Sprintf("console/%s", host), generate)
	if err != nil {
		return fmt.Errorf("failed to get/generate host key: %s", err)
	}

	signer, err := ssh.ParsePrivateKey([]byte(pemString))
	if err != nil {
		return fmt.Errorf("failed to parse host key: %s", err)
	}

	ctrl.config.AddHostKey(signer)
	return nil
}
Esempio n. 8
0
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,
	}
}
Esempio n. 9
0
File: signer.go Progetto: kalw/cfssl
// 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
	}
}
Esempio n. 10
0
// Sexp returns a well-formed S-expression for k
func (k *PrivateKey) Sexp() (s sexprs.Sexp) {
	l := make(sexprs.List, 2)
	l[0] = sexprs.Atom{Value: []byte("private-key")}
	ll := make(sexprs.List, 5)
	l[1] = ll
	ll[0] = sexprs.Atom{Value: []byte("ecdsa-sha2")}
	c := make(sexprs.List, 2)
	ll[1] = c
	c[0] = sexprs.Atom{Value: []byte("curve")}
	switch k.Curve {
	case elliptic.P256():
		c[1] = sexprs.Atom{Value: []byte("p256")}
	case elliptic.P384():
		c[1] = sexprs.Atom{Value: []byte("p384")}
	default:
		return nil
	}
	x := make(sexprs.List, 2)
	ll[2] = x
	x[0] = sexprs.Atom{Value: []byte("x")}
	x[1] = sexprs.Atom{Value: k.X.Bytes()}
	y := make(sexprs.List, 2)
	ll[3] = y
	y[0] = sexprs.Atom{Value: []byte("y")}
	y[1] = sexprs.Atom{Value: k.Y.Bytes()}
	d := make(sexprs.List, 2)
	ll[4] = d
	d[0] = sexprs.Atom{Value: []byte("d")}
	d[1] = sexprs.Atom{Value: k.D.Bytes()}
	return l
}
Esempio n. 11
0
func (j *jws) signContent(content []byte) (*jose.JsonWebSignature, error) {

	var alg jose.SignatureAlgorithm
	switch k := j.privKey.(type) {
	case *rsa.PrivateKey:
		alg = jose.RS256
	case *ecdsa.PrivateKey:
		if k.Curve == elliptic.P256() {
			alg = jose.ES256
		} else if k.Curve == elliptic.P384() {
			alg = jose.ES384
		}
	}

	signer, err := jose.NewSigner(alg, j.privKey)
	if err != nil {
		return nil, err
	}
	signer.SetNonceSource(j)

	signed, err := signer.Sign(content)
	if err != nil {
		return nil, err
	}
	return signed, nil
}
Esempio n. 12
0
func TestSignWithP384(t *testing.T) {
	message := []byte("Hello, world!")

	key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		t.Error(err)
		return
	}

	signature, err := Sign(message, key)
	if err != nil {
		t.Error(err)
		return
	}

	if !Verify(message, signature, &key.PublicKey) {
		t.Error("signature was not correct")
		return
	}

	message[0] ^= 0xff
	if Verify(message, signature, &key.PublicKey) {
		t.Error("signature was good for altered message")
	}
}
Esempio n. 13
0
// 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
	}
}
Esempio n. 14
0
// 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
	}
}
Esempio n. 15
0
File: csr.go Progetto: bbandix/cfssl
// 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")
	}
}
Esempio n. 16
0
// 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()
}
Esempio n. 17
0
// 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
}
Esempio n. 18
0
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
}
Esempio n. 19
0
// 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
}
Esempio n. 20
0
func evalECDSASHA2PrivateKeyTerms(l sexprs.List) (k PrivateKey, err error) {
	curve, err := evalCurve(l[1])
	if err != nil {
		return k, err
	}
	switch curve {
	case "p256":
		k.Curve = elliptic.P256()
	case "p384":
		k.Curve = elliptic.P384()
	default:
		return k, fmt.Errorf("Curve must be either 'p256' or 'p384'")
	}
	k.X, err = evalNamedBigInt("x", l[2])
	if err != nil {
		return k, err
	}
	k.Y, err = evalNamedBigInt("y", l[3])
	if err != nil {
		return k, err
	}
	k.D, err = evalNamedBigInt("d", l[4])
	if err != nil {
		return k, err
	}
	return k, nil
}
Esempio n. 21
0
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
}
Esempio n. 22
0
func (k *PublicKey) Sexp() (s sexprs.Sexp) {
	var curve sexprs.Atom
	switch k.Pk.Curve {
	case elliptic.P256():
		curve.Value = []byte("p256")
	case elliptic.P384():
		curve.Value = []byte("p384")
	default:
		panic(fmt.Sprintf("Bad curve value %v", k.Pk.Curve))
	}
	return sexprs.List{
		sexprs.Atom{Value: []byte("public-key")},
		sexprs.List{
			sexprs.Atom{Value: []byte("ecdsa-sha2")},
			sexprs.List{
				sexprs.Atom{Value: []byte("curve")},
				curve,
			},
			sexprs.List{
				sexprs.Atom{Value: []byte("x")},
				sexprs.Atom{Value: k.Pk.X.Bytes()},
			},
			sexprs.List{
				sexprs.Atom{Value: []byte("y")},
				sexprs.Atom{Value: k.Pk.Y.Bytes()},
			},
		},
	}
}
Esempio n. 23
0
// 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
	}
}
Esempio n. 24
0
// 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
}
Esempio n. 25
0
// 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")
	}
}
Esempio n. 26
0
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
}
Esempio n. 27
0
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
}
Esempio n. 28
0
func TestJwksSerializationPadding(t *testing.T) {
	x := new(big.Int)
	y := new(big.Int)

	e := &EssentialHeader{}
	e.KeyType = jwa.EC
	x.SetString("123520477547912006148785171019615806128401248503564636913311359802381551887648525354374204836279603443398171853465", 10)
	y.SetString("13515585925570416130130241699780319456178918334914981404162640338265336278264431930522217750520011829472589865088261", 10)
	pubKey := &ecdsa.PublicKey{
		Curve: elliptic.P384(),
		X:     x,
		Y:     y,
	}
	jwkPubKey := NewEcdsaPublicKey(pubKey)
	jwkPubKey.EssentialHeader = e
	jwkJSON, err := json.Marshal(jwkPubKey)
	if !assert.NoError(t, err, "JWK Marshalled") {
		return
	}

	_, err = Parse(jwkJSON)
	if !assert.NoError(t, err, "JWK Parsed") {
		return
	}

}
Esempio n. 29
0
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
	}
}
Esempio n. 30
0
// GenerateDefaultTLS will generate a certificate and a private key, on-the-fly
// This certificate will not be persistant (until you save it yourself)
// This is made by design to generate a new certificate at each server start, if you
// don't provide one yourself
func GenerateDefaultTLS(certPath string, keyPath string) (cert []byte, key []byte) {
	log.Info("Generating TLS certificate and key")

	rootName := "itsyou.online"
	priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)

	if err != nil {
		log.Panic("Failed to generate private key: ", err)
	}

	notBefore := time.Now()
	notAfter := notBefore.Add(4 * 365 * 24 * time.Hour) // 4 years

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		log.Panic("Failed to generate serial number: ", err)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Country:      []string{"Belgium"},
			Locality:     []string{"Lochristi"},
			Organization: []string{"It's You Online"},
			CommonName:   rootName,
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,

		DNSNames: []string{rootName},
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Panic("Failed to create certificate: ", err)
	}

	// Certificates output (in memory)

	var certOut, keyOut bytes.Buffer

	pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	b, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		log.Panic("Unable to marshal ECDSA private key: ", err)
	}

	pemUnmarsh := pem.Block{Type: "EC PRIVATE KEY", Bytes: b}

	pem.Encode(&keyOut, &pemUnmarsh)

	return certOut.Bytes(), keyOut.Bytes()
}