本文整理汇总了Golang中crypto/x509.EncryptPEMBlock函数的典型用法代码示例。如果您正苦于以下问题:Golang EncryptPEMBlock函数的具体用法?Golang EncryptPEMBlock怎么用?Golang EncryptPEMBlock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了EncryptPEMBlock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: TestProcessPrivateKeyFile_encrypted
func TestProcessPrivateKeyFile_encrypted(t *testing.T) {
// Encrypt the file
b, err := x509.EncryptPEMBlock(rand.Reader,
"RSA PRIVATE KEY",
[]byte("what"),
[]byte("password"),
x509.PEMCipherAES128)
if err != nil {
t.Fatalf("err: %s", err)
}
tf, err := ioutil.TempFile("", "packer")
if err != nil {
t.Fatalf("bad: %s", err)
}
defer os.Remove(tf.Name())
err = pem.Encode(tf, b)
tf.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
path := tf.Name()
// Should have an error with a bad password
if _, err := processPrivateKeyFile(path, "bad"); err == nil {
t.Fatal("should error")
}
if _, err := processPrivateKeyFile(path, "password"); err != nil {
t.Fatalf("bad: %s", err)
}
}
开发者ID:JNPRAutomate,项目名称:packer,代码行数:34,代码来源:private_key_test.go
示例2: 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
示例3: PrivateKeyToEncryptedPEM
// PrivateKeyToEncryptedPEM converts a private key to an encrypted PEM
func PrivateKeyToEncryptedPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
switch k := privateKey.(type) {
case *ecdsa.PrivateKey:
if k == nil {
return nil, errors.New("Invalid ecdsa private key. It must be different from nil.")
}
raw, err := x509.MarshalECPrivateKey(k)
if err != nil {
return nil, err
}
block, err := x509.EncryptPEMBlock(
rand.Reader,
"ECDSA PRIVATE KEY",
raw,
pwd,
x509.PEMCipherAES256)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(block), nil
default:
return nil, errors.New("Invalid key type. It must be *ecdsa.PrivateKey")
}
}
开发者ID:hyperledger,项目名称:fabric,代码行数:31,代码来源:keys.go
示例4: 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
示例5: PrivateKeyToEncryptedPEM
// PrivateKeyToEncryptedPEM converts a private key to an encrypted PEM
func PrivateKeyToEncryptedPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
switch x := privateKey.(type) {
case *ecdsa.PrivateKey:
raw, err := x509.MarshalECPrivateKey(x)
if err != nil {
return nil, err
}
block, err := x509.EncryptPEMBlock(
rand.Reader,
"ECDSA PRIVATE KEY",
raw,
pwd,
x509.PEMCipherAES256)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(block), nil
default:
return nil, ErrInvalidKey
}
}
开发者ID:RicHernandez2,项目名称:fabric,代码行数:27,代码来源:keys.go
示例6: writeKey
// writeKey takes an unencrypted keyblock and, if the kek is not nil, encrypts it before
// writing it to disk. If the kek is nil, writes it to disk unencrypted.
func (k *KeyReadWriter) writeKey(keyBlock *pem.Block, kekData KEKData, pkh PEMKeyHeaders) error {
if kekData.KEK != nil {
encryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
keyBlock.Type,
keyBlock.Bytes,
kekData.KEK,
x509.PEMCipherAES256)
if err != nil {
return err
}
if encryptedPEMBlock.Headers == nil {
return errors.New("unable to encrypt key - invalid PEM file produced")
}
keyBlock = encryptedPEMBlock
}
if pkh != nil {
headers, err := pkh.MarshalHeaders(kekData)
if err != nil {
return err
}
mergePEMHeaders(keyBlock.Headers, headers)
}
keyBlock.Headers[versionHeader] = strconv.FormatUint(kekData.Version, 10)
if err := ioutils.AtomicWriteFile(k.paths.Key, pem.EncodeToMemory(keyBlock), keyPerms); err != nil {
return err
}
k.kekData = kekData
k.headersObj = pkh
return nil
}
开发者ID:harche,项目名称:docker,代码行数:34,代码来源:keyreadwriter.go
示例7: EncryptPrivateKey
// EncryptPrivateKey returns an encrypted PEM key given a Privatekey
// and a passphrase
func EncryptPrivateKey(key data.PrivateKey, role, passphrase string) ([]byte, error) {
bt, err := blockType(key)
if err != nil {
return nil, err
}
password := []byte(passphrase)
cipherType := x509.PEMCipherAES256
encryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
bt,
key.Private(),
password,
cipherType)
if err != nil {
return nil, err
}
if encryptedPEMBlock.Headers == nil {
return nil, fmt.Errorf("unable to encrypt key - invalid PEM file produced")
}
encryptedPEMBlock.Headers["role"] = role
return pem.EncodeToMemory(encryptedPEMBlock), nil
}
开发者ID:sreenuyedavalli,项目名称:docker,代码行数:27,代码来源:x509utils.go
示例8: EncodePEM
func EncodePEM(binary []byte, blockType string, password string) (pemBlock string, err error) {
var blk *pem.Block
/* Awaiting Go 1.1 */
if password != "" {
passwordBytes := ([]byte)(password)
blk, err = x509.EncryptPEMBlock(rand.Reader, blockType, binary, passwordBytes, x509.PEMCipherAES256)
if err != nil {
return
}
} else {
/* */
blk = new(pem.Block)
blk.Type = blockType
blk.Bytes = binary
/* Awaiting Go 1.1 */
}
/* */
buf := new(bytes.Buffer)
err = pem.Encode(buf, blk)
if err != nil {
return
}
pemBlock = buf.String()
return
}
开发者ID:eric-hawthorne,项目名称:relish,代码行数:29,代码来源:crypto_util.go
示例9: EncryptPrivateKey
// EncryptPrivateKey returns an encrypted PEM key given a Privatekey
// and a passphrase
func EncryptPrivateKey(key *data.PrivateKey, passphrase string) ([]byte, error) {
var blockType string
algorithm := key.Algorithm()
switch algorithm {
case data.RSAKey:
blockType = "RSA PRIVATE KEY"
case data.ECDSAKey:
blockType = "EC PRIVATE KEY"
default:
return nil, fmt.Errorf("only RSA or ECDSA keys are currently supported. Found: %s", algorithm)
}
password := []byte(passphrase)
cipherType := x509.PEMCipherAES256
encryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
blockType,
key.Private(),
password,
cipherType)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(encryptedPEMBlock), nil
}
开发者ID:RichardScothern,项目名称:notary,代码行数:29,代码来源:x509utils.go
示例10: EncryptECPrivateKey
// EncryptECPrivateKey receives a PEM encoded private key and returns an encrypted
// AES256 version using a passphrase
// TODO: Make this method generic to handle RSA keys
func EncryptECPrivateKey(key []byte, passphraseStr string) ([]byte, error) {
passphrase := []byte(passphraseStr)
cipherType := x509.PEMCipherAES256
keyBlock, _ := pem.Decode(key)
if keyBlock == nil {
// This RootCA does not have a valid signer.
return nil, fmt.Errorf("error while decoding PEM key")
}
encryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
"EC PRIVATE KEY",
keyBlock.Bytes,
passphrase,
cipherType)
if err != nil {
return nil, err
}
if encryptedPEMBlock.Headers == nil {
return nil, fmt.Errorf("unable to encrypt key - invalid PEM file produced")
}
return pem.EncodeToMemory(encryptedPEMBlock), nil
}
开发者ID:yugongpeng,项目名称:swarmkit,代码行数:28,代码来源:certificates.go
示例11: exportPrivateKeytoEncryptedPEM
// export private key to pem format
func exportPrivateKeytoEncryptedPEM(sec *rsa.PrivateKey, password []byte) []byte {
l := x509.MarshalPKCS1PrivateKey(sec)
m, _ := x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", l, password, x509.PEMCipherAES256)
n := pem.EncodeToMemory(m)
//log.Print(string(n))
return n
}
开发者ID:hyg,项目名称:go.sample,代码行数:9,代码来源:main.go
示例12: EncPemKey
func (ck *RSACertKey) EncPemKey(passwd []byte) ([]byte, error) {
//kpem := ck.PemKey()
kpem := x509.MarshalPKCS1PrivateKey(ck.key)
encblock, err := x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", kpem, passwd, x509.PEMCipherAES128)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(encblock), nil
}
开发者ID:hujun-open,项目名称:manpass,代码行数:9,代码来源:pki.go
示例13: EncPkg
func (ck *ECCertKey) EncPkg(passwd string) ([]byte, error) {
var pkgpem []byte
pkgpem = append(pkgpem, ck.PemKey()...)
pkgpem = append(pkgpem, ck.PemCert()...)
encblock, err := x509.EncryptPEMBlock(rand.Reader, pkgTypeStr, pkgpem, []byte(passwd), x509.PEMCipherAES128)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(encblock), nil
}
开发者ID:hujun-open,项目名称:manpass,代码行数:10,代码来源:pki.go
示例14: _generateKey
func _generateKey(passpharse []byte, config ConfigType) (pubBlock, priBlock *pem.Block, err error) {
encodepasspharse := _passpharseHash(passpharse, config.Way)
pri, err := rsa.GenerateKey(rand.Reader, config.KeyLength)
if err != nil {
return
}
//public key encoding
pubbyte, err := x509.MarshalPKIXPublicKey(pri.Public())
if err != nil {
return
}
pubBlock, err = x509.EncryptPEMBlock(rand.Reader, "RSA PUBLIC KEY", pubbyte, []byte{}, x509.PEMCipherAES256)
if err != nil {
return
}
//private key encoding
pribyte := x509.MarshalPKCS1PrivateKey(pri)
priBlock, err = x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", pribyte, encodepasspharse, x509.PEMCipherAES256)
return
}
开发者ID:wulinxu,项目名称:KeyAdmin-go,代码行数:22,代码来源:passwordadmin.go
示例15: AEStoEncryptedPEM
// AEStoEncryptedPEM encapsulates an AES key in the encrypted PEM format
func AEStoEncryptedPEM(raw []byte, pwd []byte) ([]byte, error) {
block, err := x509.EncryptPEMBlock(
rand.Reader,
"AES PRIVATE KEY",
raw,
pwd,
x509.PEMCipherAES256)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(block), nil
}
开发者ID:masterDev1985,项目名称:obc-peer,代码行数:15,代码来源:keys.go
示例16: GenerateECDSAKeyPair
func GenerateECDSAKeyPair(keysize int, password string) (public, private []byte, err error) {
var curve elliptic.Curve
switch keysize {
case 256:
curve = elliptic.P256()
case 384:
curve = elliptic.P384()
case 521:
curve = elliptic.P521()
default:
return
}
// Generate the public/private key pair
prvKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return
}
// Marshal the public key
sshPubKey, err := ssh.NewPublicKey(&prvKey.PublicKey)
if err != nil {
return
}
public = ssh.MarshalAuthorizedKey(sshPubKey)
// Marshal the private key
prvKeyDer, err := x509.MarshalECPrivateKey(prvKey)
if err != nil {
return
}
block := &pem.Block{Type: "EC PRIVATE KEY", Bytes: prvKeyDer}
// Encrypt the private key
if len(password) != 0 {
// AES-128 is the only option for private key encryption just like in ssh-keygen.
block, err = x509.EncryptPEMBlock(rand.Reader,
"EC PRIVATE KEY",
prvKeyDer,
[]byte(password),
x509.PEMCipherAES128)
if err != nil {
return
}
}
private = pem.EncodeToMemory(block)
return
}
开发者ID:carriercomm,项目名称:MiniSSH,代码行数:49,代码来源:main.go
示例17: main
func main() {
secretMsg, err := ioutil.ReadFile("cert2.pem")
if err != nil {
fmt.Printf("ReadFile: %s\n", err)
os.Exit(1)
}
blockType := "ENCRYPTED PRIVATE KEY"
password := []byte("password")
// see http://golang.org/pkg/crypto/x509/#pkg-constants
cipherType := x509.PEMCipherAES128
EncryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
blockType,
[]byte(secretMsg),
password,
cipherType)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sDec := base64.StdEncoding.EncodeToString(EncryptedPEMBlock.Bytes)
bs := len(sDec)
// fmt.Printf("raw[%d]:\n%q\n", bs, sDec)
fmt.Printf("-----BEGIN %s-----\n", blockType)
for k, v := range EncryptedPEMBlock.Headers {
fmt.Printf("%s: %s\n", k, v)
}
fmt.Printf("\n")
nblks := bs / 64
rem := bs % 64
// fmt.Printf("nBlks = %d, rem = %d\n", nblks, rem)
for i := 0; i < nblks; i++ {
fmt.Printf("%s\n", sDec[i*64:(i+1)*64])
}
// write the remaining bs-((nblks)*64)
fmt.Printf("%s\n", sDec[bs-rem:])
fmt.Printf("-----END %s-----\n", blockType)
}
开发者ID:rabarar,项目名称:tls-example,代码行数:49,代码来源:enc.go
示例18: GenerateClient
func (crtkit *CertKit) GenerateClient(subject pkix.Name, email, password string) ([]byte, []byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, errors.New(fmt.Sprintf("failed to generate private key: %s", err))
}
notBefore := time.Now()
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return nil, nil, errors.New(fmt.Sprintf("failed to generate serial number: %s", err))
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
NotBefore: notBefore,
NotAfter: notBefore.Add(3650 * 24 * time.Hour),
EmailAddresses: []string{email},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
UnknownExtKeyUsage: []asn1.ObjectIdentifier{
[]int{1, 3, 6, 1, 4, 1, 311, 20, 2, 2}, // SmartCard Logon
[]int{1, 3, 6, 1, 4, 1, 311, 10, 3, 16}, // Verify signature for nonrepudiation?
//'1.3.6.1.4.1.311.10.3.1' => 'certTrustListSigning'
// '1.3.6.1.4.1.311.10.3.12' => 'szOID_KP_DOCUMENT_SIGNING',
},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, crtkit.CACert, &priv.PublicKey, crtkit.CAKey)
if err != nil {
return nil, nil, errors.New(fmt.Sprintf("Failed to create certificate: %s", err))
}
certOut := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
crypt_priv, err := x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(priv), []byte(password), x509.PEMCipher3DES)
if err != nil {
return nil, nil, errors.New(fmt.Sprintf("Failed to encrypt: %s", err))
}
keyOut := pem.EncodeToMemory(crypt_priv)
return certOut, keyOut, nil
}
开发者ID:luisfurquim,项目名称:stonelizard,代码行数:45,代码来源:gencert.go
示例19: ExportEncryptedPrivate
// ExportEncryptedPrivate exports encrypted PEM-format private key
func (k *Key) ExportEncryptedPrivate(password []byte) ([]byte, error) {
var privBytes []byte
switch priv := k.Private.(type) {
case *rsa.PrivateKey:
privBytes = x509.MarshalPKCS1PrivateKey(priv)
default:
return nil, errors.New("only RSA private key is supported")
}
privPEMBlock, err := x509.EncryptPEMBlock(rand.Reader, rsaPrivateKeyPEMBlockType, privBytes, password, x509.PEMCipher3DES)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
if err := pem.Encode(buf, privPEMBlock); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
开发者ID:hzy001,项目名称:etcd-ca,代码行数:21,代码来源:key.go
示例20: EncryptPemBlock
func EncryptPemBlock(block *pem.Block, password string, alg x509.PEMCipher) error {
if 0 != len(password) {
if x509.PEMCipher(0) == alg {
alg = x509.PEMCipherAES256
}
newBlock, err := x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(password), alg)
if nil != err {
return err
}
if nil == block.Headers {
block.Headers = newBlock.Headers
} else {
for hdr, val := range newBlock.Headers {
block.Headers[hdr] = val
}
}
block.Bytes = newBlock.Bytes
}
return nil
}
开发者ID:NeuralSpaz,项目名称:go-acme-client,代码行数:20,代码来源:pem.go
注:本文中的crypto/x509.EncryptPEMBlock函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论