作者:sjn197
项目:go-fuz
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
}
作者:wayf-d
项目:gosam
// 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
}
作者:vikin
项目:go-ss
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)
}
作者:wayf-d
项目:gosam
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
}
作者:hafeez300
项目:csf
// 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)
}
}
作者:postfi
项目:easypk
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
}
作者:jonathanmarven
项目:gocrypt
// 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
}
作者:djbarbe
项目:ipfs-hac
func UnmarshalRsaPrivateKey(b []byte) (*RsaPrivateKey, error) {
sk, err := x509.ParsePKCS1PrivateKey(b)
if err != nil {
return nil, err
}
return &RsaPrivateKey{sk: sk}, nil
}
作者:wulinx
项目:KeyAdmin-g
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
}
作者:hashicor
项目:terrafor
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
}
作者:ghaskin
项目:go-cluste
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")
}
作者:fatman202
项目:jas
/* 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
}
作者:tomzhan
项目:golang-devops-stuf
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
}
作者:yha
项目:workload-simulato
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)
}
作者:hermanschaa
项目:goshi
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
}
作者:tomzhan
项目:certifido
/*
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")
}
作者:kshi031
项目:gear
// 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)
}
作者:wulinx
项目:KeyAdmin-g
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
}
作者:c12simpl
项目:packe
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
}
作者:quixote
项目:vaul
// 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
}