Пример #1
0
func FuzzPKCS(data []byte) int {
	score := 0
	if k, err := x509.ParsePKCS1PrivateKey(data); err == nil {
		score = 1
		data1 := x509.MarshalPKCS1PrivateKey(k)
		k1, err := x509.ParsePKCS1PrivateKey(data1)
		if err != nil {
			panic(err)
		}
		if !fuzz.DeepEqual(k, k1) {
			panic("keys are not equal")
		}
	}
	if k0, err := x509.ParsePKCS8PrivateKey(data); err == nil {
		score = 1
		if k, ok := k0.(*rsa.PrivateKey); ok {
			data1 := x509.MarshalPKCS1PrivateKey(k)
			k1, err := x509.ParsePKCS1PrivateKey(data1)
			if err != nil {
				panic(err)
			}
			if !fuzz.DeepEqual(k, k1) {
				panic("keys are not equal")
			}
		}
	}
	return score
}
Пример #2
0
// Pem2PrivateKey converts a PEM encoded private key with an optional password to a *rsa.PrivateKey
func Pem2PrivateKey(privatekeypem, pw string) (privatekey *rsa.PrivateKey) {
	block, _ := pem.Decode([]byte(privatekeypem))
	if pw != "" {
		privbytes, _ := x509.DecryptPEMBlock(block, []byte(pw))
		privatekey, _ = x509.ParsePKCS1PrivateKey(privbytes)
	} else {
		privatekey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)
	}
	return
}
Пример #3
0
func init() {
	template.Must(configTmpl.Parse(sshd_config))
	block, _ := pem.Decode([]byte(testClientPrivateKey))
	rsakey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)

	block, _ = pem.Decode([]byte(keys["ssh_host_rsa_key"]))
	if block == nil {
		panic("pem.Decode ssh_host_rsa_key")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		panic("ParsePKCS1PrivateKey: " + err.Error())
	}
	serializedHostKey = ssh.MarshalPublicKey(&priv.PublicKey)
}
Пример #4
0
func signGo(digest []byte, privatekey, pw, algo string) (signaturevalue []byte, err error) {
	var priv *rsa.PrivateKey
	block, _ := pem.Decode([]byte(privatekey))
	if pw != "-" {
		privbytes, _ := x509.DecryptPEMBlock(block, []byte(pw))
		priv, err = x509.ParsePKCS1PrivateKey(privbytes)
	} else {
		priv, err = x509.ParsePKCS1PrivateKey(block.Bytes)
	}
	if err != nil {
		return
	}
	signaturevalue, err = rsa.SignPKCS1v15(rand.Reader, priv, algos[algo].algo, digest)
	return
}
Пример #5
0
// SetRSA reads PEM byte data and decodes it and parses the private key.
// Applies the private and the public key to the AuthManager. Password as second
// argument is only required when the private key is encrypted.
// Checks for io.Close and closes the resource. Public key will be derived from
// the private key. Default Signing bits 256.
func SetRSA(privateKey io.Reader, password ...[]byte) OptionFunc {
	if cl, ok := privateKey.(io.Closer); ok {
		defer func() {
			if err := cl.Close(); err != nil { // close file
				log.Error("userjwt.RSAKey.ioCloser", "err", err)
			}
		}()
	}
	prKeyData, errRA := ioutil.ReadAll(privateKey)
	if errRA != nil {
		return func(a *AuthManager) {
			a.lastError = errgo.Mask(errRA)
		}
	}
	var prKeyPEM *pem.Block
	if prKeyPEM, _ = pem.Decode(prKeyData); prKeyPEM == nil {
		return func(a *AuthManager) {
			a.lastError = errgo.New("Private Key from io.Reader no found")
		}
	}

	var rsaPrivateKey *rsa.PrivateKey
	var err error
	if x509.IsEncryptedPEMBlock(prKeyPEM) {
		if len(password) != 1 || len(password[0]) == 0 {
			return func(a *AuthManager) {
				a.lastError = errgo.New("Private Key is encrypted but password was not set")
			}
		}
		var dd []byte
		var errPEM error
		if dd, errPEM = x509.DecryptPEMBlock(prKeyPEM, password[0]); errPEM != nil {
			return func(a *AuthManager) {
				a.lastError = errgo.Newf("Private Key decryption failed: %s", errPEM.Error())
			}
		}
		rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(dd)
	} else {
		rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(prKeyPEM.Bytes)
	}

	return func(a *AuthManager) {
		a.SigningMethod = jwt.SigningMethodRS256
		a.rsapk = rsaPrivateKey
		a.hasKey = true
		a.lastError = errgo.Mask(err)
	}
}
Пример #6
0
func GetCA(pkiroot string) (*x509.Certificate, *rsa.PrivateKey, error) {
	caKeyBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "private", "ca.key"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca private key: %v", err)
	}
	p, _ := pem.Decode(caKeyBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca private key")
	}
	caKey, err := x509.ParsePKCS1PrivateKey(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca private key: %v", err)
	}

	caCrtBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "ca.crt"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca crt: %v", err)
	}
	p, _ = pem.Decode(caCrtBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca cert")
	}
	caCrt, err := x509.ParseCertificate(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca crt: %v", err)
	}

	return caCrt, caKey, nil
}
Пример #7
0
// ImportPEM imports an RSA key from a file. It works with both public and
// private keys.
func ImportPEM(filename string) (prv *rsa.PrivateKey, pub *rsa.PublicKey, err error) {
	cert, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	for {
		var blk *pem.Block
		blk, cert = pem.Decode(cert)
		if blk == nil {
			break
		}
		switch blk.Type {
		case "RSA PRIVATE KEY":
			prv, err = x509.ParsePKCS1PrivateKey(blk.Bytes)
			return
		case "RSA PUBLIC KEY":
			var in interface{}
			in, err = x509.ParsePKIXPublicKey(blk.Bytes)
			if err != nil {
				return
			}
			pub = in.(*rsa.PublicKey)
			return
		}
		if cert == nil || len(cert) == 0 {
			break
		}
	}
	return
}
Пример #8
0
func UnmarshalRsaPrivateKey(b []byte) (*RsaPrivateKey, error) {
	sk, err := x509.ParsePKCS1PrivateKey(b)
	if err != nil {
		return nil, err
	}
	return &RsaPrivateKey{sk: sk}, nil
}
Пример #9
0
func _passwordListDecoding(encodedpassword [][]byte, passpharse []byte, priblock *pem.Block) (password [][]byte, err error) {
	//decode with base64
	encodedpasswordList := make([][]byte, len(encodedpassword))
	for i, e := range encodedpassword {
		encodedpasswordList[i], err = base64.StdEncoding.DecodeString(string(e))
		if err != nil {
			return
		}
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password = make([][]byte, len(encodedpasswordList))
	for i, e := range encodedpasswordList {
		password[i], err = rsa.DecryptPKCS1v15(rand.Reader, pri, e)
	}

	if err != nil {
		return
	}

	return
}
func getSshKey(d *schema.ResourceData, path string) (privatekey string, publickey string, err error) {
	pemBytes, err := ioutil.ReadFile(path)

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

	block, _ := pem.Decode(pemBytes)

	if block == nil {
		return "", "", errors.New("File " + path + " contains nothing")
	}

	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

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

	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(priv),
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return "", "", err
	}
	publickey = string(ssh.MarshalAuthorizedKey(pub))
	privatekey = string(pem.EncodeToMemory(&priv_blk))

	return privatekey, publickey, nil
}
Пример #11
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")
}
Пример #12
0
/* With help from:
 * https://stackoverflow.com/questions/14404757/how-to-encrypt-and-decrypt-plain-text-with-a-rsa-keys-in-go
 */
func getRSAKeyFromSSHFile(keyFile string) (key *rsa.PrivateKey) {
	verbose(fmt.Sprintf("Extracting RSA key from '%s'...", keyFile), 3)

	pemData, err := ioutil.ReadFile(keyFile)
	if err != nil {
		fail(fmt.Sprintf("Unable to read '%s'.\n", keyFile))
	}

	block, _ := pem.Decode(pemData)
	if block == nil {
		fail(fmt.Sprintf("Unable to PEM-decode '%s'.\n", keyFile))
	}

	if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
		fail(fmt.Sprintf("Unknown key type %q.\n", got))
	}

	keyBytes := block.Bytes
	if strings.Contains(string(pemData), "Proc-Type: 4,ENCRYPTED") {

		password := getpass(fmt.Sprintf("Enter pass phrase for %s: ", keyFile))
		keyBytes, err = x509.DecryptPEMBlock(block, password)
		if err != nil {
			fail(fmt.Sprintf("Unable to decrypt private key: %v\n", err))
		}
	}

	key, err = x509.ParsePKCS1PrivateKey(keyBytes)
	if err != nil {
		fail(fmt.Sprintf("Unable to extract private key from PEM data: %v\n", err))
	}
	return
}
Пример #13
0
func (k *Keychain) AddPEMKey(privateKeyPath string) error {
	var rsakey interface{}
	var err error

	keyContent, err := ioutil.ReadFile(privateKeyPath)
	if err != nil {
		return err
	}

	block, _ := pem.Decode([]byte(keyContent))
	if block == nil {
		return errors.New("no block in key")
	}

	rsakey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		rsakey, err = x509.ParsePKCS8PrivateKey(block.Bytes)
	}

	if err != nil {
		return err
	}

	k.keys = append(k.keys, rsakey)

	return nil
}
Пример #14
0
func parseKey(data []byte) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode(data)
	if block == nil {
		return nil, errors.New("no block in PEM data")
	}
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}
Пример #15
0
func remoteCmdOutput(username, hostname, privateKey, cmd string) []byte {
	block, _ := pem.Decode([]byte(privateKey))
	rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	clientKey := &keychain{rsakey}
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthKeyring(clientKey),
		},
	}
	client, err := ssh.Dial("tcp", hostname, clientConfig)
	if err != nil {
		log.Println("ERROR: Failed to dial: " + err.Error())
		return []byte{}
	}
	session, err := client.NewSession()
	if err != nil {
		log.Println("ERROR: Failed to create session: " + err.Error())
		return []byte{}
	}
	defer session.Close()
	output, err := session.Output(cmd)
	if err != nil {
		log.Printf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
		return []byte{}
	}
	return output
}
Пример #16
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")
}
Пример #17
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)
}
Пример #18
0
func _passwordDecoding(encodedpassword, passpharse []byte, priblock *pem.Block) (password []byte, err error) {
	//decode with base64
	_encodedpassword, err := base64.StdEncoding.DecodeString(string(encodedpassword))
	if err != nil {
		return
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password, err = rsa.DecryptPKCS1v15(rand.Reader, pri, _encodedpassword)

	if err != nil {
		return
	}

	return
}
Пример #19
0
func decryptPasswordDataWithPrivateKey(passwordData string, pemBytes []byte) (string, error) {
	encryptedPasswd, err := base64.StdEncoding.DecodeString(passwordData)
	if err != nil {
		return "", err
	}

	block, _ := pem.Decode(pemBytes)
	var asn1Bytes []byte
	if _, ok := block.Headers["DEK-Info"]; ok {
		return "", errors.New("encrypted private key isn't yet supported")
		/*
			asn1Bytes, err = x509.DecryptPEMBlock(block, password)
			if err != nil {
				return "", err
			}
		*/
	} else {
		asn1Bytes = block.Bytes
	}

	key, err := x509.ParsePKCS1PrivateKey(asn1Bytes)
	if err != nil {
		return "", err
	}

	out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd)
	if err != nil {
		return "", err
	}

	return string(out), nil
}
Пример #20
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
}
Пример #21
0
func main() {
	block, _ := pem.Decode([]byte(rsaPrivateKey))
	rsaPriv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse private key: %s", err)
	}

	req := &x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: "CapiTalizedLetters.com",
		},
		DNSNames: []string{
			"moreCAPs.com",
			"morecaps.com",
			"evenMOREcaps.com",
			"Capitalizedletters.COM",
		},
	}
	csr, err := x509.CreateCertificateRequest(rand.Reader, req, rsaPriv)
	if err != nil {
		log.Fatalf("unable to create CSR: %s", err)
	}
	_, err = os.Stdout.Write(csr)
	if err != nil {
		log.Fatalf("unable to write to stdout: %s", err)
	}
}
Пример #22
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)
}
Пример #23
0
func getPrivateKey() *rsa.PrivateKey {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
	}
	privateKeyFile, err := os.Open(dir + "/utils/" + settings.PrivateKeyPath)
	if err != nil {
		panic(err)
	}

	pemfileinfo, _ := privateKeyFile.Stat()
	var size int64 = pemfileinfo.Size()
	pembytes := make([]byte, size)

	buffer := bufio.NewReader(privateKeyFile)
	_, err = buffer.Read(pembytes)

	data, _ := pem.Decode([]byte(pembytes))

	privateKeyFile.Close()

	privateKeyImported, err := x509.ParsePKCS1PrivateKey(data.Bytes)

	if err != nil {
		panic(err)
	}

	return privateKeyImported
}
Пример #24
0
// WriteAuthenticatedDataPackage creates an AuthenticatedDataPackage
// containing the specified data and signed by the given key. The output
// conforms with the legacy format here:
// https://bitbucket.org/psiphon/psiphon-circumvention-system/src/c25d080f6827b141fe637050ce0d5bd0ae2e9db5/Automation/psi_ops_crypto_tools.py
func WriteAuthenticatedDataPackage(
	data string, signingPublicKey, signingPrivateKey string) ([]byte, error) {

	derEncodedPrivateKey, err := base64.StdEncoding.DecodeString(signingPrivateKey)
	if err != nil {
		return nil, ContextError(err)
	}
	rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(derEncodedPrivateKey)
	if err != nil {
		return nil, ContextError(err)
	}

	signature, err := rsa.SignPKCS1v15(
		rand.Reader,
		rsaPrivateKey,
		crypto.SHA256,
		sha256sum(data))
	if err != nil {
		return nil, ContextError(err)
	}

	packageJSON, err := json.Marshal(
		&AuthenticatedDataPackage{
			Data: data,
			SigningPublicKeyDigest: sha256sum(signingPublicKey),
			Signature:              signature,
		})
	if err != nil {
		return nil, ContextError(err)
	}

	return packageJSON, nil
}
Пример #25
0
func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
Пример #26
0
func benchmarkLatency(b *testing.B, block int) {
	// Override the overlay configuration
	swapConfigs()
	defer swapConfigs()

	b.SetBytes(int64(block))
	key, _ := x509.ParsePKCS1PrivateKey(privKeyDer)

	// Generate a batch of messages to send around
	head := proto.Header{[]byte{0x99, 0x98, 0x97, 0x96}, []byte{0x00, 0x01}, []byte{0x02, 0x03}}
	msgs := make([]proto.Message, b.N)
	for i := 0; i < b.N; i++ {
		msgs[i].Head = head
		msgs[i].Data = make([]byte, block)
		io.ReadFull(rand.Reader, msgs[i].Data)
		msgs[i].Encrypt()
	}
	// Create the sender node
	send := New(appId, key, new(nopCallback))
	send.Boot()
	defer send.Shutdown()

	// Create the receiver app to sequence messages and the associated overlay node
	recvApp := &sequencer{send, nil, msgs, b.N, make(chan struct{})}
	recv := New(appId, key, recvApp)
	recvApp.dest = recv.nodeId
	recv.Boot()
	defer recv.Shutdown()

	// Reset timer and start message passing
	b.ResetTimer()
	recvApp.Deliver(nil, nil)
	<-recvApp.quit
	b.StopTimer()
}
Пример #27
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)
}
Пример #28
0
// GetPrivateKey returns private key
func (a Account) GetPrivateKey() crypto.PrivateKey {
	if privateKey, err := x509.ParsePKCS1PrivateKey(a.PrivateKey); err == nil {
		return privateKey
	}
	log.Errorf("Cannot unmarshall private key %+v", a.PrivateKey)
	return nil
}
Пример #29
0
func ParsePEMEncodedPrivateKey(pemdata []byte) (*rsa.PrivateKey, error) {
	decoded, _ := pem.Decode(pemdata)
	if decoded == nil {
		return nil, errors.New("no PEM data found")
	}
	return x509.ParsePKCS1PrivateKey(decoded.Bytes)
}
Пример #30
0
// Should be run only once.
func loadPrivateKey() error {
	pathToKey, cfgErr := cfg.GetStr(cfg.STR_KEYS_PATH)
	if cfgErr != nil {
		return cfgErr
	}

	pemData, err := ioutil.ReadFile(pathToKey + "private_key.pem")
	if err != nil {
		return err
	}

	block, _ := pem.Decode(pemData)
	if block == nil {
		return errors.New("Pem block is empty.")
	}
	if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
		return errors.New("Invalid pem block.")
	}

	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return errors.New("Bad private key.")
	}

	privateKey = priv

	return nil
}