當前位置: 首頁>>代碼示例>>Golang>>正文


Golang x509.DecryptPEMBlock函數代碼示例

本文整理匯總了Golang中crypto/x509.DecryptPEMBlock函數的典型用法代碼示例。如果您正苦於以下問題:Golang DecryptPEMBlock函數的具體用法?Golang DecryptPEMBlock怎麽用?Golang DecryptPEMBlock使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了DecryptPEMBlock函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ParsePEMPrivateKey

// 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)
	}
}
開發者ID:RichardScothern,項目名稱:notary,代碼行數:62,代碼來源:x509utils.go

示例2: FuzzPEM

func FuzzPEM(data []byte) int {
	var b pem.Block
	err := gob.NewDecoder(bytes.NewReader(data)).Decode(&b)
	if err != nil {
		return 0
	}
	b1, err := x509.DecryptPEMBlock(&b, []byte("pass"))
	if err != nil {
		return 0
	}
	b2, err := x509.EncryptPEMBlock(zeroReader(0), "msg", b1, []byte("pass1"), x509.PEMCipherDES)
	if err != nil {
		panic(err)
	}
	_, err = x509.DecryptPEMBlock(b2, []byte("pass"))
	if err == nil {
		panic("decoded with a wrong pass")
	}
	b3, err := x509.DecryptPEMBlock(b2, []byte("pass1"))
	if err != nil {
		panic(err)
	}
	if !bytes.Equal(b1, b3) {
		panic("data changed")
	}
	return 1
}
開發者ID:sjn1978,項目名稱:go-fuzz,代碼行數:27,代碼來源:main.go

示例3: checkKey

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)
			}
		}
	}
}
開發者ID:a-yiorgos,項目名稱:delaporter,代碼行數:28,代碼來源:delaporter.go

示例4: SSHConfigPubKeyFile

// SSHConfigPubKeyFile is a convience function that takes a username, private key
// and passphrase and returns a new ssh.ClientConfig setup to pass credentials
// to DialSSH
func SSHConfigPubKeyFile(user string, file string, passphrase string) (*ssh.ClientConfig, error) {
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	block, rest := pem.Decode(buf)
	if len(rest) > 0 {
		return nil, fmt.Errorf("pem: unable to decode file %s", file)
	}

	if x509.IsEncryptedPEMBlock(block) {
		b := block.Bytes
		b, err = x509.DecryptPEMBlock(block, []byte(passphrase))
		if err != nil {
			return nil, err
		}
		buf = pem.EncodeToMemory(&pem.Block{
			Type:  block.Type,
			Bytes: b,
		})
	}

	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		return nil, err
	}
	return &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(key),
		},
	}, nil

}
開發者ID:Juniper,項目名稱:go-netconf,代碼行數:37,代碼來源:transport_ssh.go

示例5: LoadCertKeyFromEncPkg

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")

}
開發者ID:hujun-open,項目名稱:manpass,代碼行數:60,代碼來源:pki.go

示例6: readKeyOrGenerate

func readKeyOrGenerate(path, pass string) (*rsa.PrivateKey, error) {
	file, err := ioutil.ReadFile(path)
	var key *rsa.PrivateKey
	if err != nil {
		log.Printf("Generating new key %s...", path)
		key, err = rsa.GenerateKey(rand.Reader, rsaBitLength)
		if err != nil {
			return nil, err
		}
		raw := x509.MarshalPKCS1PrivateKey(key)
		block, err := x509.EncryptPEMBlock(rand.Reader, blockType, raw, []byte(pass), cipherType)
		if err != nil {
			return nil, err
		}
		encoded := pem.EncodeToMemory(block)
		ioutil.WriteFile(path, encoded, 0400)
	} else {
		log.Printf("Loading key %s...", path)
		block, _ := pem.Decode(file)
		if block == nil {
			return nil, fmt.Errorf("%s doesn't contain a PEM key", path)
		}
		raw, err := x509.DecryptPEMBlock(block, []byte(pass))
		if err != nil {
			return nil, err
		}
		key, err = x509.ParsePKCS1PrivateKey(raw)
		if err != nil {
			return nil, err
		}
	}
	return key, nil
}
開發者ID:d4l3k,項目名稱:upass,代碼行數:33,代碼來源:crypto.go

示例7: decryptPEM

func decryptPEM(pemblock *pem.Block, filename string) ([]byte, error) {
	var err error
	if _, err = fmt.Fprintf(os.Stderr, "Enter passphrase for %s: ", filename); err != nil {
		return []byte(""), err
	}

	// we already emit the prompt to stderr; GetPass only emits to stdout
	var passwd string
	passwd, err = gopass.GetPass("")
	fmt.Fprintln(os.Stderr, "")
	if err != nil {
		return []byte(""), err
	}

	var decryptedBytes []byte
	if decryptedBytes, err = x509.DecryptPEMBlock(pemblock, []byte(passwd)); err != nil {
		return []byte(""), err
	}

	pemBytes := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: decryptedBytes,
	}
	decryptedPEM := pem.EncodeToMemory(&pemBytes)
	return decryptedPEM, nil
}
開發者ID:realestate-com-au,項目名稱:credulous,代碼行數:26,代碼來源:credulous.go

示例8: readKey

// readKey returns the decrypted key pem bytes, and enforces the KEK if applicable
// (writes it back with the correct encryption if it is not correctly encrypted)
func (k *KeyReadWriter) readKey() (*pem.Block, error) {
	keyBlock, err := k.readKeyblock()
	if err != nil {
		return nil, err
	}

	if !x509.IsEncryptedPEMBlock(keyBlock) {
		return keyBlock, nil
	}

	// If it's encrypted, we can't read without a passphrase (we're assuming
	// empty passphrases iare invalid)
	if k.kekData.KEK == nil {
		return nil, ErrInvalidKEK{Wrapped: x509.IncorrectPasswordError}
	}

	derBytes, err := x509.DecryptPEMBlock(keyBlock, k.kekData.KEK)
	if err != nil {
		return nil, ErrInvalidKEK{Wrapped: err}
	}
	// remove encryption PEM headers
	headers := make(map[string]string)
	mergePEMHeaders(headers, keyBlock.Headers)

	return &pem.Block{
		Type:    keyBlock.Type, // the key type doesn't change
		Bytes:   derBytes,
		Headers: headers,
	}, nil
}
開發者ID:harche,項目名稱:docker,代碼行數:32,代碼來源:keyreadwriter.go

示例9: _passwordDecoding

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
}
開發者ID:wulinxu,項目名稱:KeyAdmin-go,代碼行數:26,代碼來源:passwordadmin.go

示例10: ReadDecryptRsaPrivKeyFromReader

func (crtkit CertKit) ReadDecryptRsaPrivKeyFromReader(r io.Reader) (*rsa.PrivateKey, []byte, error) {
	var err error
	var pembuf []byte
	var key *rsa.PrivateKey
	var plainkey []byte
	var block *pem.Block

	pembuf, err = ioutil.ReadAll(r)
	if err != nil {
		Goose.Loader.Logf(1, "Failed reading Key %s", err)
		return nil, nil, err
	}

	block, _ = pem.Decode(pembuf)

	plainkey, err = x509.DecryptPEMBlock(block, []byte{})
	Goose.Loader.Logf(1, "DecryptPEMBlock: %s", plainkey)
	if err != nil {
		return nil, nil, err
	}

	key, err = x509.ParsePKCS1PrivateKey(plainkey)
	if err != nil {
		Goose.Loader.Logf(1, "Failed parsing key %s", err)
		return nil, nil, err
	}

	return key, pem.EncodeToMemory(&pem.Block{
		Type: "RSA PRIVATE KEY",
		//    Headers map[string]string // Optional headers.
		Bytes: plainkey,
	}), nil
}
開發者ID:luisfurquim,項目名稱:stonelizard,代碼行數:33,代碼來源:util.go

示例11: PEMtoPublicKey

// PEMtoPublicKey unmarshals a pem to public key
func PEMtoPublicKey(raw []byte, pwd []byte) (interface{}, error) {
	block, _ := pem.Decode(raw)
	// TODO: derive from header the type of the key

	if x509.IsEncryptedPEMBlock(block) {
		if pwd == nil {
			return nil, errors.New("Encrypted Key. Need a password!!!")
		}

		decrypted, err := x509.DecryptPEMBlock(block, pwd)
		if err != nil {
			return nil, errors.New("Failed decryption!!!")
		}

		key, err := DERToPublicKey(decrypted)
		if err != nil {
			return nil, err
		}
		return key, err
	}

	cert, err := DERToPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return cert, err
}
開發者ID:RicHernandez2,項目名稱:fabric,代碼行數:28,代碼來源:keys.go

示例12: processPrivateKeyFile

// processPrivateKeyFile takes a private key file and an optional passphrase
// and decodes it to a byte slice.
func processPrivateKeyFile(privateKeyFile, passphrase string) ([]byte, error) {
	rawPrivateKeyBytes, err := ioutil.ReadFile(privateKeyFile)
	if err != nil {
		return nil, fmt.Errorf("Failed loading private key file: %s", err)
	}

	PEMBlock, _ := pem.Decode(rawPrivateKeyBytes)
	if PEMBlock == nil {
		return nil, fmt.Errorf(
			"%s does not contain a vaild private key", privateKeyFile)
	}

	if x509.IsEncryptedPEMBlock(PEMBlock) {
		if passphrase == "" {
			return nil, errors.New("a passphrase must be specified when using an encrypted private key")
		}

		decryptedPrivateKeyBytes, err := x509.DecryptPEMBlock(PEMBlock, []byte(passphrase))
		if err != nil {
			return nil, fmt.Errorf("Failed decrypting private key: %s", err)
		}

		b := &pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: decryptedPrivateKeyBytes,
		}
		return pem.EncodeToMemory(b), nil
	}

	return rawPrivateKeyBytes, nil
}
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:33,代碼來源:private_key.go

示例13: DecodePEM

/*
Given a PEM block in a string e.g.
----- BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClbkoOcBAXWJpRh9x+qEHRVvLs
DjatUqRN/rHmH3rZkdjFEFb/7bFitMDyg6EqiKOU3/Umq3KRy7MHzqv84LHf1c2V
CAltWyuLbfXWce9jd8CSHLI8Jwpw4lmOb/idGfEFrMLT8Ms18pKA4Thrb2TE7yLh
4fINDOjP+yJJvZohNwIDAQAB
----- END RSA PUBLIC KEY-----
Returns the decoding of the base-64 into a byte slice.
Also returns the block type, in this case "RSA PUBLIC KEY"
*/
func DecodePEM(pemBlock string, password string) (decoded []byte, blockType string, err error) {

	var blk *pem.Block
	pb := ([]byte)(pemBlock)

	blk, _ = pem.Decode(pb)
	if blk == nil {
		err = errors.New("DecodePEM: No PEM block found.")
		return
	}

	/* Awaiting Go 1.1 */
	if password != "" {
		passwordBytes := ([]byte)(password)
		decoded, err = x509.DecryptPEMBlock(blk, passwordBytes)
	} else {
		/* */
		decoded = blk.Bytes
		/* Awaiting Go 1.1 */
	}
	/* */

	blockType = blk.Type
	return
}
開發者ID:eric-hawthorne,項目名稱:relish,代碼行數:36,代碼來源:crypto_util.go

示例14: ReadPrivateKey

// ReadPrivateKey attempts to read your private key and possibly decrypt it if it
// requires a passphrase.
// This function will prompt for a passphrase on STDIN if the environment variable (`IDENTITY_PASSPHRASE`),
// is not set.
func ReadPrivateKey(path string) ([]byte, error) {
	privateKey, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to load identity: %v", err)
	}

	block, rest := pem.Decode(privateKey)
	if len(rest) > 0 {
		return nil, fmt.Errorf("extra data when decoding private key")
	}
	if !x509.IsEncryptedPEMBlock(block) {
		return privateKey, nil
	}

	passphrase := os.Getenv("IDENTITY_PASSPHRASE")
	if passphrase == "" {
		passphrase, err = gopass.GetPass("Enter passphrase: ")
		if err != nil {
			return nil, fmt.Errorf("couldn't read passphrase: %v", err)
		}
	}
	der, err := x509.DecryptPEMBlock(block, []byte(passphrase))
	if err != nil {
		return nil, fmt.Errorf("decrypt failed: %v", err)
	}

	privateKey = pem.EncodeToMemory(&pem.Block{
		Type:  block.Type,
		Bytes: der,
	})

	return privateKey, nil
}
開發者ID:dream1986,項目名稱:ssh-chat,代碼行數:37,代碼來源:key.go

示例15: _passwordListDecoding

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
}
開發者ID:wulinxu,項目名稱:KeyAdmin-go,代碼行數:32,代碼來源:passwordadmin.go


注:本文中的crypto/x509.DecryptPEMBlock函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。