Beispiel #1
0
func checkKey(jobs <-chan string, wg *sync.WaitGroup, block *pem.Block) {
	// https://github.com/golang/go/issues/10171
	// golang's fix? expand the documentation ...
	defer wg.Done()
	for passwordStr := range jobs {
		password := []byte(passwordStr)
		key, err := x509.DecryptPEMBlock(block, password)
		if err == nil {
			// we now have a candidate, is it random noise or is can be parsed?
			// for some reason ParseRawPrivateKey fails so its brute force time
			// https://github.com/golang/go/issues/8581 - ed25519 are not currently supported by Golang
			_, err := ssh.ParseDSAPrivateKey(key)
			if err == nil {
				printNDie(password)
			}
			// not DSA? maybe RSA
			_, err = x509.ParsePKCS1PrivateKey(key)
			if err == nil {
				printNDie(password)
			}
			// ECDSA?
			_, err = x509.ParseECPrivateKey(key)
			if err == nil {
				printNDie(password)
			}
		}
	}
}
Beispiel #2
0
// DecodePrivateKey decodes a PEM-encoded ECDSA private key.
func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error) {
	var skippedTypes []string
	var block *pem.Block

	for {
		block, encodedKey = pem.Decode(encodedKey)

		if block == nil {
			return nil, fmt.Errorf("failed to find EC PRIVATE KEY in PEM data after skipping types %v", skippedTypes)
		}

		if block.Type == "EC PRIVATE KEY" {
			break
		} else {
			skippedTypes = append(skippedTypes, block.Type)
			continue
		}
	}

	privKey, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	return privKey, nil
}
Beispiel #3
0
// ParsePEMPrivateKey returns a data.PrivateKey from a PEM encoded private key. It
// only supports RSA (PKCS#1) and attempts to decrypt using the passphrase, if encrypted.
func ParsePEMPrivateKey(pemBytes []byte, passphrase string) (*data.PrivateKey, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("no valid private key found")
	}

	switch block.Type {
	case "RSA PRIVATE KEY":
		var privKeyBytes []byte
		var err error

		if x509.IsEncryptedPEMBlock(block) {
			privKeyBytes, err = x509.DecryptPEMBlock(block, []byte(passphrase))
			if err != nil {
				return nil, errors.New("could not decrypt private key")
			}
		} else {
			privKeyBytes = block.Bytes
		}

		rsaPrivKey, err := x509.ParsePKCS1PrivateKey(privKeyBytes)
		if err != nil {
			return nil, fmt.Errorf("could not parse DER encoded key: %v", err)
		}

		tufRSAPrivateKey, err := RSAToPrivateKey(rsaPrivKey, data.RSAKey)
		if err != nil {
			return nil, fmt.Errorf("could not convert rsa.PrivateKey to data.PrivateKey: %v", err)
		}

		return tufRSAPrivateKey, nil
	case "EC PRIVATE KEY":
		var privKeyBytes []byte
		var err error

		if x509.IsEncryptedPEMBlock(block) {
			privKeyBytes, err = x509.DecryptPEMBlock(block, []byte(passphrase))
			if err != nil {
				return nil, errors.New("could not decrypt private key")
			}
		} else {
			privKeyBytes = block.Bytes
		}

		ecdsaPrivKey, err := x509.ParseECPrivateKey(privKeyBytes)
		if err != nil {
			return nil, fmt.Errorf("could not parse DER encoded private key: %v", err)
		}

		tufECDSAPrivateKey, err := ECDSAToPrivateKey(ecdsaPrivKey, data.ECDSAKey)
		if err != nil {
			return nil, fmt.Errorf("could not convert ecdsa.PrivateKey to data.PrivateKey: %v", err)
		}

		return tufECDSAPrivateKey, nil

	default:
		return nil, fmt.Errorf("unsupported key type %q", block.Type)
	}
}
Beispiel #4
0
// Sign calculates a signature for a byte array hash using hex-encoded private key
// It is supposed that a hash is calculated for an original message to sign
// Signature is a hex-encoded JSON
func Sign(hash []byte, private_key_hex string) (signature_hex string, err error) {
	// decode private key from hex
	private_key_bytes, err := hex.DecodeString(private_key_hex)
	if err != nil {
		return "", err
	}

	// x509 parse private key
	private_key, err := x509.ParseECPrivateKey(private_key_bytes)
	if err != nil {
		return "", err
	}

	// sign
	r, s, err := ecdsa.Sign(rand.Reader, private_key, hash)
	if err != nil {
		return "", err
	}

	// prepare a signature structure to marshal into json
	signature := &signature{
		R: r,
		S: s,
	}

	// marshal to json
	signature_json, err := json.Marshal(signature)
	if err != nil {
		return "", err
	}

	// encode to hex
	signature_hex = hex.EncodeToString(signature_json)
	return signature_hex, nil
}
Beispiel #5
0
func LoadCertKeyFromEncPkg(encpkg []byte, passwd string) (*CertKey, error) {
	blk, _ := pem.Decode(encpkg)
	if blk == nil {
		return nil, errors.New("Invalid PEM data")
	}
	if blk.Type != pkgTypeStr {
		return nil, errors.New("PEM type is not " + pkgTypeStr)
	}
	decrypted_pem, err := x509.DecryptPEMBlock(blk, []byte(passwd))
	if err != nil {
		return nil, err
	}
	key_pem, rest := pem.Decode(decrypted_pem)
	if blk == nil {
		return nil, errors.New("decrypted content is not PEM")
	}
	cert_pem, _ := pem.Decode(rest)
	if blk == nil {
		return nil, errors.New("Can't find the cert PEM")
	}
	if _, ok := supportedKeyTypes[key_pem.Type]; !ok {
		return nil, errors.New("Unsupported Key types")
	}
	if cert_pem.Type != "CERTIFICATE" {
		return nil, errors.New("Can't find certificate in decrypted PEM data")
	}
	var ck CertKey
	switch key_pem.Type {
	case "RSA PRIVATE KEY":
		rsack := new(RSACertKey)
		priv_key, err := x509.ParsePKCS1PrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.cert = *cert[0]
		ck = rsack
		return &ck, nil
	case "EC PRIVATE KEY":
		ecck := new(ECCertKey)
		priv_key, err := x509.ParseECPrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.cert = *cert[0]
		ck = ecck
		return &ck, nil
	}
	return nil, errors.New("Unussal error, you shouldn't see this")

}
Beispiel #6
0
// ParseAndEncode takes key, certificate, and optional password
// as []byte and parses them to get a suitable format to encode them
func ParseAndEncode(key, cert, password []byte) string {
	var file string
	certBlock, _ := pem.Decode(cert)
	certBytes := certBlock.Bytes
	certificate, err := x509.ParseCertificate(certBytes)
	if err != nil {
		return file
	}

	block, _ := pem.Decode(key)
	privKey := block.Bytes
	if block.Type == "RSA PRIVATE KEY" {
		pkcsKey, err := x509.ParsePKCS1PrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(pkcsKey, certificate, password)
	} else if block.Type == "EC PRIVATE KEY" {
		ecKey, err := x509.ParseECPrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(ecKey, certificate, password)
	}

	return file
}
Beispiel #7
0
func loadECertAndEnrollmentPrivateKey(enrollmentID string, password string) ([]byte, *ecdsa.PrivateKey, error) {
	cooked, err := ioutil.ReadFile("./test_resources/key_" + enrollmentID + ".dump")
	if err != nil {
		return nil, nil, err
	}

	block, _ := pem.Decode(cooked)
	decryptedBlock, err := x509.DecryptPEMBlock(block, []byte(password))
	if err != nil {
		return nil, nil, err
	}

	enrollmentPrivateKey, err := x509.ParseECPrivateKey(decryptedBlock)
	if err != nil {
		return nil, nil, err
	}

	if err != nil {
		return nil, nil, err
	}

	ecertRaw, err := ioutil.ReadFile("./test_resources/ecert_" + enrollmentID + ".dump")
	if err != nil {
		return nil, nil, err
	}

	return ecertRaw, enrollmentPrivateKey, nil
}
Beispiel #8
0
// FinishKEX verifies the signed public key. If it is valid, it will
// carry out an ECDH key agreement, zeroise the private key, and store
// the shared key.
func (kex *Session) FinishKEX(signer *ecdsa.PublicKey, signed []byte) error {
	var skey signedKey
	rest, err := asn1.Unmarshal(signed, &skey)
	if err != nil {
		return err
	} else if len(rest) != 0 {
		return errors.New("eckex: trailing data in key exchange")
	}

	hashed := sha256.Sum256(skey.Public)

	if !ecdsa.Verify(signer, hashed[:], skey.R, skey.S) {
		return errors.New("eckex: verification failure")
	}

	pub, err := unpackECPKIX(skey.Public)
	if err != nil {
		return err
	}

	priv, err := x509.ParseECPrivateKey(kex.priv)
	util.Zero(kex.priv)
	if err != nil {
		return err
	}

	kex.shared, err = nistecdh.ECDH(priv, pub)
	kex.shared = kex.shared[:32]
	return err
}
Beispiel #9
0
// ParsePrivateKeyPEM parses and returns a PEM-encoded private
// key. The private key may be either an unencrypted PKCS#8, PKCS#1,
// or elliptic private key.
func ParsePrivateKeyPEM(keyPEM []byte) (key interface{}, err error) {
	keyDER, _ := pem.Decode(keyPEM)
	if keyDER == nil {
		return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed, nil)
	}
	if procType, ok := keyDER.Headers["Proc-Type"]; ok {
		if strings.Contains(procType, "ENCRYPTED") {
			return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted, nil)
		}
	}
	key, err = x509.ParsePKCS8PrivateKey(keyDER.Bytes)
	if err != nil {
		key, err = x509.ParsePKCS1PrivateKey(keyDER.Bytes)
		if err != nil {
			key, err = x509.ParseECPrivateKey(keyDER.Bytes)
			if err != nil {
				// We don't include the actual error into the final error.
				// The reason might be we don't want to leak any info about
				// the private key.
				return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed, nil)
			}
		}
	}
	return
}
Beispiel #10
0
// addKey parses an SSH private key for execd. It takes in the SSH server configuration and the key to add.
// It returns an error if the key is unsupported by execd.
func addKey(conf *ssh.ServerConfig, block *pem.Block) (err error) {
	var key interface{}

	switch block.Type {
	case "RSA PRIVATE KEY":
		key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
	case "EC PRIVATE KEY":
		key, err = x509.ParseECPrivateKey(block.Bytes)
	case "DSA PRIVATE KEY":
		key, err = ssh.ParseDSAPrivateKey(block.Bytes)
	default:
		return fmt.Errorf("unsupported key type %q", block.Type)
	}
	if err != nil {
		return err
	}

	signer, err := ssh.NewSignerFromKey(key)
	if err != nil {
		return err
	}

	conf.AddHostKey(signer)

	return nil
}
Beispiel #11
0
func TestECDSAGenerateKeyAndCSR(t *testing.T) {
	var si = SubjectInfo{
		Country:    "US",
		CommonName: "localhost",
	}

	pemKey, csr, err := GenerateKeyAndCSR(ECDSA, 256, &si)
	if err != nil {
		t.Fatalf("%v", err)
	}

	p, _ := pem.Decode(pemKey)
	if p == nil {
		t.Fatal("csr: invalid PEM-encoded ECDSA key")
	} else if p.Type != "EC PRIVATE KEY" {
		t.Fatal("csr: invalid PEM-encoded ECDSA key")
	}

	priv, err := x509.ParseECPrivateKey(p.Bytes)
	if err != nil {
		t.Fatal("csr: invalid PEM-encoded ECDSA key")
	} else if priv.Curve != elliptic.P256() {
		t.Fatal("csr: invalid PEM-encoded ECDSA key")
	}

	_, err = ParseCertificateRequest(csr)
	if err != nil {
		t.Fatalf("%v", err)
	}
}
Beispiel #12
0
// import private key from pem format
func importPrivateKeyfromPEM(pemsec []byte) *ecdsa.PrivateKey {
	block, _ := pem.Decode(pemsec)
	//log.Print(block)
	sec, _ := x509.ParseECPrivateKey(block.Bytes)
	//log.Print(sec)
	return sec
}
Beispiel #13
0
// ParsePublicKey parses a PEM encoded private key. Currently, only
// PKCS#1, RSA and ECDSA private keys are supported.
func ParsePrivateKey(pemBytes []byte) (Signer, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("ssh: no key found")
	}

	var rawkey interface{}
	switch block.Type {
	case "RSA PRIVATE KEY":
		rsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = rsa
	case "EC PRIVATE KEY":
		ec, err := x509.ParseECPrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = ec

		// TODO(hanwen): find doc for format and implement PEM parsing
		// for DSA keys.
	default:
		return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
	}

	return NewSignerFromKey(rawkey)
}
Beispiel #14
0
// ParsePrivateKeyDER parses a PKCS #1, PKCS #8, or elliptic curve
// DER-encoded private key. The key must not be in PEM format.
func ParsePrivateKeyDER(keyDER []byte) (key crypto.Signer, err error) {
	generalKey, err := x509.ParsePKCS8PrivateKey(keyDER)
	if err != nil {
		generalKey, err = x509.ParsePKCS1PrivateKey(keyDER)
		if err != nil {
			generalKey, err = x509.ParseECPrivateKey(keyDER)
			if err != nil {
				// We don't include the actual error into
				// the final error. The reason might be
				// we don't want to leak any info about
				// the private key.
				return nil, cferr.New(cferr.PrivateKeyError,
					cferr.ParseFailed)
			}
		}
	}

	switch generalKey.(type) {
	case *rsa.PrivateKey:
		return generalKey.(*rsa.PrivateKey), nil
	case *ecdsa.PrivateKey:
		return generalKey.(*ecdsa.PrivateKey), nil
	}

	// should never reach here
	return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed)
}
Beispiel #15
0
// LoadPrivateKey loads a private key from PEM/DER-encoded data.
func LoadPrivateKey(data []byte) (interface{}, error) {
	input := data

	block, _ := pem.Decode(data)
	if block != nil {
		input = block.Bytes
	}

	var priv interface{}
	priv, err0 := x509.ParsePKCS1PrivateKey(input)
	if err0 == nil {
		return priv, nil
	}

	priv, err1 := x509.ParsePKCS8PrivateKey(input)
	if err1 == nil {
		return priv, nil
	}

	priv, err2 := x509.ParseECPrivateKey(input)
	if err2 == nil {
		return priv, nil
	}

	return nil, fmt.Errorf("square/go-jose: parse error, got '%s', '%s' and '%s'", err0, err1, err2)
}
// GetKeyECC returns the ECDSA private key of the record given the correct password.
func (pr PasswordRecord) GetKeyECC(password string) (key *ecdsa.PrivateKey, err error) {
	if pr.Type != ECCRecord {
		return key, errors.New("Invalid function for record type")
	}

	if err = pr.ValidatePassword(password); err != nil {
		return
	}

	passKey, err := derivePasswordKey(password, pr.KeySalt)
	if err != nil {
		return
	}

	x509Padded, err := symcrypt.DecryptCBC(pr.ECKey.ECPriv, pr.ECKey.ECPrivIV, passKey)
	if err != nil {
		return
	}

	ecX509, err := padding.RemovePadding(x509Padded)
	if err != nil {
		return
	}
	return x509.ParseECPrivateKey(ecX509)
}
Beispiel #17
0
func parseKey(path string) (crypto.PublicKey, error) {

	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, errors.New("failed to open key file \"" + path + "\"")
	}

	block, _ := pem.Decode(buf)
	if block.Type != "PRIVATE KEY" && strings.HasSuffix(block.Type, " PRIVATE KEY") == false {
		return nil, errors.New("private key PEM does not appear to contain a private key blob")
	}

	der := block.Bytes
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		case *rsa.PrivateKey, *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("failed to parse private key")
}
Beispiel #18
0
// GetSigner returns a crypto.Signer corresponding to the private key
// contained in this ParsedCSRBundle. The Signer contains a Public() function
// for getting the corresponding public. The Signer can also be
// type-converted to private keys
func (p *ParsedCSRBundle) getSigner() (crypto.Signer, error) {
	var signer crypto.Signer
	var err error

	if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 {
		return nil, errutil.UserError{"Given parsed cert bundle does not have private key information"}
	}

	switch p.PrivateKeyType {
	case ECPrivateKey:
		signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes)
		if err != nil {
			return nil, errutil.UserError{fmt.Sprintf("Unable to parse CA's private EC key: %s", err)}
		}

	case RSAPrivateKey:
		signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes)
		if err != nil {
			return nil, errutil.UserError{fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)}
		}

	default:
		return nil, errutil.UserError{"Unable to determine type of private key; only RSA and EC are supported"}
	}
	return signer, nil
}
Beispiel #19
0
func ecdsaSign(privKey data.PrivateKey, hashed []byte) ([]byte, error) {
	if _, ok := privKey.(*data.ECDSAPrivateKey); !ok {
		return nil, fmt.Errorf("private key type not supported: %s", privKey.Algorithm())
	}

	// Create an ecdsa.PrivateKey out of the private key bytes
	ecdsaPrivKey, err := x509.ParseECPrivateKey(privKey.Private())
	if err != nil {
		return nil, err
	}

	// Use the ECDSA key to sign the data
	r, s, err := ecdsa.Sign(rand.Reader, ecdsaPrivKey, hashed[:])
	if err != nil {
		return nil, err
	}

	rBytes, sBytes := r.Bytes(), s.Bytes()
	octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3

	// MUST include leading zeros in the output
	rBuf := make([]byte, octetLength-len(rBytes), octetLength)
	sBuf := make([]byte, octetLength-len(sBytes), octetLength)

	rBuf = append(rBuf, rBytes...)
	sBuf = append(sBuf, sBytes...)

	return append(rBuf, sBuf...), nil
}
Beispiel #20
0
func init() {
	var err error
	var pemBytes []byte
	var key crypto.Signer
	var p *pem.Block

	s, err = NewServerFromFile(certFile, keyFile, caFile, addr, os.Stdout)
	if err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParsePKCS1PrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)

	if pemBytes, err = ioutil.ReadFile(ecdsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParseECPrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)
}
Beispiel #21
0
// ParsePublicKey parses a PEM encoded private key. It supports
// PKCS#1, RSA, DSA and ECDSA private keys.
func ParsePrivateKey(pemBytes []byte) (Signer, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("ssh: no key found")
	}

	var rawkey interface{}
	switch block.Type {
	case "RSA PRIVATE KEY":
		rsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = rsa
	case "EC PRIVATE KEY":
		ec, err := x509.ParseECPrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = ec
	case "DSA PRIVATE KEY":
		ec, err := parseDSAPrivate(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = ec
	default:
		return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
	}

	return NewSignerFromKey(rawkey)
}
Beispiel #22
0
/*
  Reads and returns the next DER-encoded private key from r,
  which may optionally be base64 encoded (PEM format)
  and may be preceded by "garbage" (PEM headers).
  This function takes care not to read more bytes than
  necessary which allows the function to be called
  multiple times on a stream of concatenated keys.
*/
func ReadNextKey(in io.Reader) (crypto.Signer, error) {
	data, err := ReadNextSEQUENCE(in)
	if err != nil {
		return nil, err
	}
	key1, err1 := x509.ParseECPrivateKey(data)
	key2, err2 := x509.ParsePKCS1PrivateKey(data)
	key3, err3 := x509.ParsePKCS8PrivateKey(data)
	if err1 == nil {
		return key1, nil
	}
	if err2 == nil {
		return key2, nil
	}
	if err3 != nil {
		return nil, err3
	}
	switch key := key3.(type) {
	case *rsa.PrivateKey:
		return key, nil
	case *ecdsa.PrivateKey:
		return key, nil
	}
	return nil, fmt.Errorf("Unknown key type in PKCS8 container")
}
func TestUnlockedSigner(t *testing.T) {
	privKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
	assert.NoError(t, err, "could not generate key")

	keyStore := trustmanager.NewKeyMemoryStore(passphraseRetriever)

	err = keyStore.AddKey(privKey.ID(), "root", privKey)
	assert.NoError(t, err, "could not add key to store")

	cryptoService := NewCryptoService("", keyStore)
	uCryptoService := NewUnlockedCryptoService(privKey, cryptoService)

	// Check ID method
	assert.Equal(t, privKey.ID(), uCryptoService.ID())

	// Check Public method
	assert.Equal(t, privKey.Public(), uCryptoService.PublicKey().Public())
	assert.Equal(t, privKey.ID(), uCryptoService.PublicKey().ID())

	// Check GenerateCertificate method
	gun := "docker.com/notary"
	cert, err := uCryptoService.GenerateCertificate(gun)
	assert.NoError(t, err, "could not generate certificate")

	// Check public key
	ecdsaPrivateKey, err := x509.ParseECPrivateKey(privKey.Private())
	assert.NoError(t, err)
	ecdsaPublicKey := ecdsaPrivateKey.Public()
	assert.Equal(t, ecdsaPublicKey, cert.PublicKey)

	// Check CommonName
	assert.Equal(t, cert.Subject.CommonName, gun)
}
Beispiel #24
0
// ParseECPrivateKeyFromPEM will parse a PEM encoded EC Private
// Key Structure.
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
	block, _ := pem.Decode(key)
	if block == nil {
		return nil, ErrKeyMustBePEMEncoded
	}
	return x509.ParseECPrivateKey(block.Bytes)
}
Beispiel #25
0
// UnmarshalPrivateKeyPEM parses the PEM encoded data and returns a libtrust
// PrivateKey or an error if there is a problem with the encoding.
func UnmarshalPrivateKeyPEM(data []byte) (PrivateKey, error) {
	pemBlock, _ := pem.Decode(data)
	if pemBlock == nil {
		return nil, errors.New("unable to find PEM encoded data")
	}

	var key PrivateKey

	switch {
	case pemBlock.Type == "RSA PRIVATE KEY":
		rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
		if err != nil {
			return nil, fmt.Errorf("unable to decode RSA Private Key PEM data: %s", err)
		}
		key = fromRSAPrivateKey(rsaPrivateKey)
	case pemBlock.Type == "EC PRIVATE KEY":
		ecPrivateKey, err := x509.ParseECPrivateKey(pemBlock.Bytes)
		if err != nil {
			return nil, fmt.Errorf("unable to decode EC Private Key PEM data: %s", err)
		}
		key, err = fromECPrivateKey(ecPrivateKey)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("unable to get PrivateKey from PEM type: %s", pemBlock.Type)
	}

	addPEMHeadersToKey(pemBlock, key.PublicKey())

	return key, nil
}
Beispiel #26
0
func init() {
	// Sample key generated with
	// http://play.golang.org/p/SYdIwEX5oj
	buf, _ := base64.StdEncoding.DecodeString(`MGgCAQEEHGVPTAPaVNX4YmbVyfTYW8FWJMpZCo2R9HChDH6gBwYFK4EEACGhPAM6AAQU2Bbh+7LCIFwTYas4CZyPJ1QKL9hnWGFPTrpF4LawRo8j40KLu0A9ickIzi0dCN+CrA9gxWO8yA==`)
	key, _ := x509.ParseECPrivateKey(buf)
	reader = &testReader{rand.NewSource(123)}
	signer = &testSigner{key}
}
Beispiel #27
0
func ReadKey(path string) (*PrivateKey, error) {
	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	key, err := x509.ParseECPrivateKey(buf)
	return (*PrivateKey)(key), err
}
Beispiel #28
0
// import private key from pem format
func importPrivateKeyfromEncryptedPEM(pemsec, password []byte) *ecdsa.PrivateKey {
	block, _ := pem.Decode(pemsec)
	//log.Print(block)
	buf, _ := x509.DecryptPEMBlock(block, password)
	sec, _ := x509.ParseECPrivateKey(buf)
	//log.Print(sec)
	return sec
}
Beispiel #29
0
func dumpECKey(der []byte) (err error) {
	key, err := x509.ParseECPrivateKey(der)
	if err != nil {
		return
	}
	printECKey(key)
	return
}
Beispiel #30
0
func LoadManpassCA(uname string, passwd []byte) (*CertKey, error) {
	//generate a new EE cert/key with specified uname's CA
	//return encrypted CA cert, EE cert and encrypted EE key in a string
	confdir := common.GetConfDir(uname)
	fi, err := os.Stat(confdir)
	if err != nil {
		return nil, err
	}
	if !fi.IsDir() {
		return nil, fmt.Errorf("%s is not a directory", confdir)
	}
	encacs, err := ioutil.ReadFile(filepath.Join(confdir, "ca.cert"))
	if err != nil {
		return nil, err
	}
	cacert_der, err := passcrypto.DecryptMeBase32(string(encacs), passwd)
	if err != nil {
		return nil, err
	}
	encaks, err := ioutil.ReadFile(filepath.Join(confdir, "ca.key"))
	if err != nil {
		return nil, err
	}
	blk, _ := pem.Decode(encaks)
	cakey_der, err := x509.DecryptPEMBlock(blk, passwd)
	var ck CertKey
	switch blk.Type {
	case "RSA PRIVATE KEY":
		ca := new(RSACertKey)
		cakey, err := x509.ParsePKCS1PrivateKey(cakey_der)
		if err != nil {
			return nil, err
		}
		ca.key = cakey
		cert, err := x509.ParseCertificates(cacert_der)
		if err != nil {
			return nil, err
		}
		ca.cert = *cert[0]
		ck = ca
		return &ck, nil
	case "EC PRIVATE KEY":
		ecck := new(ECCertKey)
		priv_key, err := x509.ParseECPrivateKey(cakey_der)
		if err != nil {
			return nil, err
		}
		ecck.key = priv_key
		cert, err := x509.ParseCertificates(cacert_der)
		if err != nil {
			return nil, err
		}
		ecck.cert = *cert[0]
		ck = ecck
		return &ck, nil
	}
	return nil, errors.New("Unussal error, you shouldn't see this")
}