本文整理汇总了Golang中encoding/pem.Block.Bytes方法的典型用法代码示例。如果您正苦于以下问题:Golang Block.Bytes方法的具体用法?Golang Block.Bytes怎么用?Golang Block.Bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类encoding/pem.Block
的用法示例。
在下文中一共展示了Block.Bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ToCSRBundle
// ToCSRBundle converts a byte-based raw DER certificate bundle
// to a PEM-based string certificate bundle
func (p *ParsedCSRBundle) ToCSRBundle() (*CSRBundle, error) {
result := &CSRBundle{}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
}
if p.CSRBytes != nil && len(p.CSRBytes) > 0 {
block.Bytes = p.CSRBytes
result.CSR = strings.TrimSpace(string(pem.EncodeToMemory(&block)))
}
if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 {
block.Bytes = p.PrivateKeyBytes
switch p.PrivateKeyType {
case RSAPrivateKey:
result.PrivateKeyType = "rsa"
block.Type = "RSA PRIVATE KEY"
case ECPrivateKey:
result.PrivateKeyType = "ec"
block.Type = "EC PRIVATE KEY"
default:
return nil, errutil.InternalError{"Could not determine private key type when creating block"}
}
result.PrivateKey = strings.TrimSpace(string(pem.EncodeToMemory(&block)))
}
return result, nil
}
示例2: GenKeyPairIfNone
func GenKeyPairIfNone(privateName string, publicName string) {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
privatekey := filepath.Join(dir, privateName)
publickey := filepath.Join(dir, publicName)
if _, err := os.Stat(string(privatekey)); os.IsNotExist(err) {
log.Println("Generating JWT private key at ", string(privatekey))
k, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
var private pem.Block
private.Type = "RSA PRIVATE KEY"
private.Bytes = x509.MarshalPKCS1PrivateKey(k)
pp := new(bytes.Buffer)
pem.Encode(pp, &private)
err = ioutil.WriteFile(string(privatekey), pp.Bytes(), 0644)
if err != nil {
log.Fatal(err)
}
log.Println("Generating JWT public key at ", string(privatekey))
var public pem.Block
public.Type = "RSA PUBLIC KEY"
public.Bytes, _ = x509.MarshalPKIXPublicKey(&k.PublicKey)
ps := new(bytes.Buffer)
pem.Encode(ps, &public)
err = ioutil.WriteFile(string(publickey), ps.Bytes(), 0644)
if err != nil {
log.Fatal(err)
}
}
}
示例3: ReadPEMData
// Read a PEM file and ask for a password to decrypt it if needed
func ReadPEMData(pemFile string, pemPass []byte) ([]byte, error) {
pemData, err := ioutil.ReadFile(pemFile)
if err != nil {
return pemData, err
}
// We should really just get the pem.Block back here, if there's other
// junk on the end, warn about it.
pemBlock, rest := pem.Decode(pemData)
if len(rest) > 0 {
log.Warning("Didn't parse all of", pemFile)
}
if x509.IsEncryptedPEMBlock(pemBlock) {
// Decrypt and get the ASN.1 DER bytes here
pemData, err = x509.DecryptPEMBlock(pemBlock, pemPass)
if err != nil {
return pemData, err
} else {
log.Info("Decrypted", pemFile, "successfully")
}
// Shove the decrypted DER bytes into a new pem Block with blank headers
var newBlock pem.Block
newBlock.Type = pemBlock.Type
newBlock.Bytes = pemData
// This is now like reading in an uncrypted key from a file and stuffing it
// into a byte stream
pemData = pem.EncodeToMemory(&newBlock)
}
return pemData, nil
}
示例4: 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
}
示例5: Marshal
func (pk *PrivateKey) Marshal(ss ...string) ([]byte, error) {
var k = x509.MarshalPKCS1PrivateKey(&pk.PrivateKey)
var block pem.Block
block.Bytes = k
block.Type = strings.Join(ss, " ")
return pem.EncodeToMemory(&block), nil
}
示例6: encrypt
func encrypt(key []byte, keytype Type, password string) (out []byte, err error) {
cryptkey, iv, err := encryptKey(key, password)
if err != nil {
return
}
var block pem.Block
switch keytype {
case KEY_RSA:
block.Type = "RSA PRIVATE KEY"
case KEY_ECDSA:
block.Type = "EC PRIVATE KEY"
case KEY_DSA:
block.Type = "DSA PRIVATE KEY"
default:
err = ErrInvalidPrivateKey
return
}
block.Bytes = cryptkey
block.Headers = make(map[string]string)
block.Headers["Proc-Type"] = "4,ENCRYPTED"
block.Headers["DEK-Info"] = fmt.Sprintf("AES-128-CBC,%X", iv)
out = pem.EncodeToMemory(&block)
return
}
示例7: CertificateLockFile
// CertificateLockFile adds a new certificate lock on the given Client and
// Config that ensures that a server's certificate is signed by the same CA
// from connection-to-connection. This is helpful when connecting to servers
// with self-signed certificates.
//
// If filename does not exist, the server's certificate chain will be written
// to that file. If it does exist, certificates will be read from that file and
// added to RootCAs in config's TLSConfig.
//
// Example:
//
// if firstConnectionToServer {
// // Allow self-signed certificates to be accepted on the initial
// // connection.
// config.TLSConfig.InsecureSkipVerify = true
// }
// gumbleutil.CertificateLockFile(client, &config, filename)
//
// if err := client.Connect(); err != nil {
// panic(err)
// }
func CertificateLockFile(client *gumble.Client, config *gumble.Config, filename string) (gumble.Detacher, error) {
if file, err := os.Open(filename); err == nil {
defer file.Close()
if config.TLSConfig.RootCAs == nil {
config.TLSConfig.RootCAs = x509.NewCertPool()
}
if data, err := ioutil.ReadAll(file); err == nil {
config.TLSConfig.RootCAs.AppendCertsFromPEM(data)
}
return nil, nil
}
return client.Attach(Listener{
Connect: func(e *gumble.ConnectEvent) {
tlsClient, ok := e.Client.Conn().(*tls.Conn)
if !ok {
return
}
serverCerts := tlsClient.ConnectionState().PeerCertificates
file, err := os.Create(filename)
if err != nil {
return
}
block := pem.Block{
Type: "CERTIFICATE",
}
for _, cert := range serverCerts {
block.Bytes = cert.Raw
pem.Encode(file, &block)
}
file.Close()
},
}), nil
}
示例8: execSSH
func execSSH(url, uuid string, key *rsa.PrivateKey, args []string) error {
f, err := ioutil.TempFile("", "runx")
if err != nil {
return fmt.Errorf("tmpfile: %s", err)
}
defer f.Close()
var b pem.Block
b.Type = "RSA PRIVATE KEY"
b.Bytes = x509.MarshalPKCS1PrivateKey(key)
if err = pem.Encode(f, &b); err != nil {
return fmt.Errorf("pem: %s", err)
}
f.Seek(0, 0)
argv := []string{
"ssh",
"-i" + f.Name(),
"-oProxyCommand=hk runx [proxy]",
"-oLocalCommand=rm " + f.Name(),
"-oStrictHostKeyChecking=no",
"-oUserKnownHostsFile=/dev/null",
"[email protected]" + uuid,
}
env := append(os.Environ(), "RUNX_URL="+url)
return syscall.Exec("/usr/bin/ssh", append(argv, args...), env)
}
示例9: MarshalPrivate
// Given a private key and a (possibly empty) password, returns a byte
// slice containing a PEM-encoded private key in the appropriate
// OpenSSH format.
func MarshalPrivate(priv interface{}, password string) (out []byte, err error) {
var (
keytype Type
der []byte
btype string
)
switch priv.(type) {
case *rsa.PrivateKey:
keytype = KEY_RSA
der = x509.MarshalPKCS1PrivateKey(priv.(*rsa.PrivateKey))
if der == nil {
err = ErrInvalidPrivateKey
return
}
btype = "RSA PRIVATE KEY"
case *ecdsa.PrivateKey:
keytype = KEY_ECDSA
der, err = marshalECDSAKey(priv.(*ecdsa.PrivateKey))
btype = "EC PRIVATE KEY"
case *dsa.PrivateKey:
keytype = KEY_DSA
dsakey := priv.(*dsa.PrivateKey)
k := struct {
Version int
P *big.Int
Q *big.Int
G *big.Int
Priv *big.Int
Pub *big.Int
}{
Version: 1,
P: dsakey.PublicKey.P,
Q: dsakey.PublicKey.Q,
G: dsakey.PublicKey.G,
Priv: dsakey.PublicKey.Y,
Pub: dsakey.X,
}
der, err = asn1.Marshal(k)
if err != nil {
return
}
btype = "DSA PRIVATE KEY"
default:
err = ErrInvalidPrivateKey
return
}
if password != "" {
out, err = encrypt(der, keytype, password)
return
}
var block pem.Block
block.Type = btype
block.Bytes = der
out = pem.EncodeToMemory(&block)
return
}
示例10: readPEMFile
func readPEMFile(path, passphrase string) ([]byte, error) {
pass := []byte(passphrase)
var blocks []*pem.Block
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
for len(content) > 0 {
var block *pem.Block
block, content = pem.Decode(content)
if block == nil {
if len(blocks) == 0 {
return nil, errors.New("no pem file")
}
break
}
if x509.IsEncryptedPEMBlock(block) {
var buffer []byte
var err error
if len(pass) == 0 {
err = errors.New("No passphrase available")
} else {
// Note, decrypting pem might succeed even with wrong password, but
// only noise will be stored in buffer in this case.
buffer, err = x509.DecryptPEMBlock(block, pass)
}
if err != nil {
logp.Err("Dropping encrypted pem '%v' block read from %v. %v",
block.Type, path, err)
continue
}
// DEK-Info contains encryption info. Remove header to mark block as
// unencrypted.
delete(block.Headers, "DEK-Info")
block.Bytes = buffer
}
blocks = append(blocks, block)
}
if len(blocks) == 0 {
return nil, errors.New("no PEM blocks")
}
// re-encode available, decrypted blocks
buffer := bytes.NewBuffer(nil)
for _, block := range blocks {
err := pem.Encode(buffer, block)
if err != nil {
return nil, err
}
}
return buffer.Bytes(), nil
}
示例11: convertBag
func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
b := new(pem.Block)
for _, attribute := range bag.Attributes {
k, v, err := convertAttribute(&attribute)
if err != nil {
return nil, err
}
if b.Headers == nil {
b.Headers = make(map[string]string)
}
b.Headers[k] = v
}
switch {
case bag.ID.Equal(oidCertBagType):
b.Type = CertificateType
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, err
}
b.Bytes = certsData
case bag.ID.Equal(oidPkcs8ShroudedKeyBagType):
b.Type = PrivateKeyType
key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
if err != nil {
return nil, err
}
switch key := key.(type) {
case *rsa.PrivateKey:
b.Bytes = x509.MarshalPKCS1PrivateKey(key)
case *ecdsa.PrivateKey:
b.Bytes, err = x509.MarshalECPrivateKey(key)
if err != nil {
return nil, err
}
default:
return nil, errors.New("found unknown private key type in PKCS#8 wrapping")
}
default:
return nil, errors.New("don't know how to convert a safe bag of type " + bag.ID.String())
}
return b, nil
}
示例12: main
func main() {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
pubkey := key.Public()
bytes, _ := x509.MarshalECPrivateKey(key)
block := pem.Block{}
block.Bytes = bytes
block.Type = "EC PRIVATE KEY"
bytes_encoded := pem.EncodeToMemory(&block)
fmt.Println(string(bytes_encoded))
if err != nil {
fmt.Println(err)
}
bytes, _ = x509.MarshalPKIXPublicKey(pubkey)
block = pem.Block{}
block.Type = "EC PUBLIC KEY"
block.Bytes = bytes
bytes_encoded = pem.EncodeToMemory(&block)
fmt.Println(string(bytes_encoded))
if err != nil {
fmt.Println(err)
}
// dat, err := ioutil.ReadFile("prime256v1-key.pem")
// pemblock, _ := pem.Decode(dat)
// check(err)
// privkey, parseerr := x509.ParseECPrivateKey(pemblock.Bytes)
//
// if parseerr != nil {
// fmt.Println(err)
// }
//
// bytes, _ = x509.MarshalECPrivateKey(privkey)
// block = pem.Block{}
// block.Bytes = bytes
// block.Type = "EC PRIVATE KEY"
// bytes_encoded = pem.EncodeToMemory(&block)
// fmt.Println(string(bytes_encoded))
}
示例13: byteToPEM
func byteToPEM(b []byte, t PEMType) []byte {
var blk pem.Block = pem.Block{
Type: string(t),
Headers: nil,
}
blk.Bytes = b
data := pem.EncodeToMemory(&blk)
return data
}
示例14: main
func main() {
k, err := rsa.GenerateKey(rand.Reader, 768)
if err != nil {
log.Fatal(err)
}
var b pem.Block
b.Type = "RSA PRIVATE KEY"
b.Bytes = x509.MarshalPKCS1PrivateKey(k)
pem.Encode(os.Stdout, &b)
}
示例15: saveKey
func saveKey(keyPath string, key crypto.PrivateKey) error {
if fileExists(keyPath) {
return nil
}
f, err := os.Create(keyPath)
if err != nil {
return err
}
w := bufio.NewWriter(f)
defer f.Close()
var block pem.Block
switch i := key.(type) {
case *ecdsa.PrivateKey:
// TODO: How do we encode and save the parameters of the curve? Do we need to?
key := key.(*ecdsa.PrivateKey)
b, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
block.Type = "EC PARAMETERS"
err = pem.Encode(w, &block)
block.Type = "EC PRIVATE KEY"
block.Bytes = b
case *rsa.PrivateKey:
k := x509.MarshalPKCS1PrivateKey(key.(*rsa.PrivateKey))
block.Type = "RSA PRIVATE KEY"
block.Bytes = k
default:
fmt.Println(i)
return new(unknownKeyError)
}
err = pem.Encode(w, &block)
if err != nil {
return err
}
return w.Flush()
}