本文整理汇总了Golang中crypto/x509.MarshalPKCS1PrivateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang MarshalPKCS1PrivateKey函数的具体用法?Golang MarshalPKCS1PrivateKey怎么用?Golang MarshalPKCS1PrivateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MarshalPKCS1PrivateKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: FuzzPKCS
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: GenerateRSAKeys
// GenerateRSAKeys creates a pair of private and public keys for a client.
func GenerateRSAKeys() (string, string, error) {
/* Shamelessly borrowed and adapted from some golang-samples */
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", err
}
if err := priv.Validate(); err != nil {
errStr := fmt.Errorf("RSA key validation failed: %s", err)
return "", "", errStr
}
privDer := x509.MarshalPKCS1PrivateKey(priv)
/* For some reason chef doesn't label the keys RSA PRIVATE/PUBLIC KEY */
privBlk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDer,
}
privPem := string(pem.EncodeToMemory(&privBlk))
pub := priv.PublicKey
pubDer, err := x509.MarshalPKIXPublicKey(&pub)
if err != nil {
errStr := fmt.Errorf("Failed to get der format for public key: %s", err)
return "", "", errStr
}
pubBlk := pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: pubDer,
}
pubPem := string(pem.EncodeToMemory(&pubBlk))
return privPem, pubPem, nil
}
示例3: marshalPKCS8PrivateKey
// marshalPKCS8PrivateKey converts a private key to PKCS#8 encoded form.
// See http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
func marshalPKCS8PrivateKey(key interface{}) (der []byte, err error) {
pkcs := pkcs8{
Version: 0,
}
switch key := key.(type) {
case *rsa.PrivateKey:
pkcs.Algo = pkix.AlgorithmIdentifier{
Algorithm: oidPublicKeyRSA,
Parameters: nullAsn,
}
pkcs.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
case *ecdsa.PrivateKey:
bytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, errors.New("x509: failed to marshal to PKCS#8: " + err.Error())
}
pkcs.Algo = pkix.AlgorithmIdentifier{
Algorithm: oidPublicKeyECDSA,
Parameters: nullAsn,
}
pkcs.PrivateKey = bytes
default:
return nil, errors.New("x509: PKCS#8 only RSA and ECDSA private keys supported")
}
bytes, err := asn1.Marshal(pkcs)
if err != nil {
return nil, errors.New("x509: failed to marshal to PKCS#8: " + err.Error())
}
return bytes, nil
}
示例4: GenerateKeyPair
/*
Generates an RSA key pair of the specified key length in bits.
Uses Go's crypto/rand rand.Reader as the source of entropy.
If password is a non-empty string, encrypts the private key so that password is required
to decrypt and use it. If password == "", the private key returned is unencrypted.
*/
func GenerateKeyPair(keyLenBits int, password string) (privateKeyPEM string, publicKeyPEM string, err error) {
priv, err := rsa.GenerateKey(rand.Reader, keyLenBits)
if err != nil {
return
}
err = priv.Validate()
if err != nil {
return
}
privateKeyBytes := x509.MarshalPKCS1PrivateKey(priv)
privateKeyPEM, err = EncodePrivateKeyPEM(privateKeyBytes, password)
if err != nil {
return
}
pub := &(priv.PublicKey)
publicKeyBytes, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
return
}
publicKeyPEM, err = EncodePublicKeyPEM(publicKeyBytes)
if err != nil {
return
}
return
}
示例5: getSshKey
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
}
示例6: makeCert
// makeCert creates a self-signed RSA certificate.
// taken from crypto/tls/generate_cert.go
func makeCert(host string, validFor time.Duration) (certPEM, keyPEM []byte) {
const bits = 1024
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
log.Fatalf("Failed to generate private key: %s", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Fabio Co"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(validFor),
IsCA: true,
DNSNames: []string{host},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
var cert, key bytes.Buffer
pem.Encode(&cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(&key, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return cert.Bytes(), key.Bytes()
}
示例7: GenerateServer
func (crtkit *CertKit) GenerateServer(subject pkix.Name, host, email string, NotBefore ...time.Time) error {
var e error
var derBytes []byte
var notBefore time.Time
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return errors.New(fmt.Sprintf("failed to generate private key: %s", err))
}
if len(NotBefore) > 0 {
notBefore = NotBefore[0]
} else {
notBefore = time.Now()
}
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return errors.New(fmt.Sprintf("failed to generate serial number: %s", err))
}
if host == "" {
host, _ = os.Hostname()
}
Goose.Generator.Logf(6, "Certificate authority used: %#v", crtkit.CACert)
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
IsCA: false,
NotBefore: notBefore,
NotAfter: notBefore.Add(365 * 24 * time.Hour),
DNSNames: []string{host, strings.Split(host, ".")[0]},
AuthorityKeyId: crtkit.CACert.SubjectKeyId,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageContentCommitment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
Goose.Generator.Logf(4, "X509 Template: %#v", template)
if crtkit.CACert.CRLDistributionPoints != nil {
template.CRLDistributionPoints = crtkit.CACert.CRLDistributionPoints
} else {
Goose.Generator.Logf(1, "Certificate authority without CRL distribution points")
}
crtkit.ServerKey = priv
crtkit.ServerCert = &template
derBytes, e = x509.CreateCertificate(rand.Reader, &template, crtkit.CACert, &priv.PublicKey, crtkit.CAKey)
if e != nil {
return errors.New(fmt.Sprintf("Failed to create certificate: %s", e))
}
Goose.Generator.Logf(4, "DER Certificate: %s", derBytes)
crtkit.ServerCertPem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
crtkit.ServerKeyPem = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
Goose.Generator.Logf(4, "PEM Certificate: %s", crtkit.ServerCertPem)
return nil
}
示例8: GenerateSelfSignedCert
// GenerateSelfSignedCert creates a self-signed certificate and key for the given host.
// Host may be an IP or a DNS name
// The certificate will be created with file mode 0644. The key will be created with file mode 0600.
// If the certificate or key files already exist, they will be overwritten.
// Any parent directories of the certPath or keyPath will be created as needed with file mode 0755.
func GenerateSelfSignedCert(host, certPath, keyPath string) error {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: fmt.Sprintf("%[email protected]%d", host, time.Now().Unix()),
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 365),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
if ip := net.ParseIP(host); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, host)
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return err
}
// Generate cert
certBuffer := bytes.Buffer{}
if err := pem.Encode(&certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
// Generate key
keyBuffer := bytes.Buffer{}
if err := pem.Encode(&keyBuffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
return err
}
// Write cert
if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
return err
}
if err := ioutil.WriteFile(certPath, certBuffer.Bytes(), os.FileMode(0644)); err != nil {
return err
}
// Write key
if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
return err
}
if err := ioutil.WriteFile(keyPath, keyBuffer.Bytes(), os.FileMode(0600)); err != nil {
return err
}
return nil
}
示例9: installKey
// TODO: install functions should be defined on an interface. Composed implementations
// would persist to various stores. This implementation will use mounted tmpfs, but others
// might include some vault.
func installKey(key *rsa.PrivateKey, location string) error {
pkDirPrepTimeStart := time.Now()
dir := path.Dir(location)
// Create destination directory
if err := syscall.Mkdir(dir, 0600); err != nil {
if err != syscall.EEXIST {
return err
}
// The directory already exists
log.Printf("The key destination directory already exists.")
}
// with CAP_SYS_ADMIN we could create a tmpfs mount
if err := syscall.Mount("tmpfs", dir, "tmpfs", 0600, "size=1M"); err != nil {
log.Printf("Unable to create tmpfs mount. Do you have CAP_SYS_ADMIN? Error: %s", err)
}
log.Printf("[TIMER] [%s] Prepared PK storage\n", time.Since(pkDirPrepTimeStart))
keyOut, err := os.OpenFile(location, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer keyOut.Close()
if err != nil {
log.Print("failed to open key.pem for writing:", err)
return nil
}
pkFileWriteTimeStart := time.Now()
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
log.Printf("[TIMER] [%s] Wrote PK\n", time.Since(pkFileWriteTimeStart))
return nil
}
示例10: generateKeyAndCert
//TODO (diogo): Add support for EC P384
func generateKeyAndCert(gun string) (crypto.PrivateKey, *x509.Certificate, error) {
// Generates a new RSA key
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("could not generate private key: %v", err)
}
keyBytes := x509.MarshalPKCS1PrivateKey(key)
// Creates a new Certificate template. We need the certificate to calculate the
// TUF-compliant keyID
//TODO (diogo): We're hardcoding the Organization to be the GUN. Probably want to
// change it
template := newCertificate(gun, gun)
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate the certificate for key: %v", err)
}
// Encode the new certificate into PEM
cert, err := x509.ParseCertificate(derBytes)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate the certificate for key: %v", err)
}
kID := trustmanager.FingerprintCert(cert)
// The key is going to be stored in the private directory, using the GUN and
// the filename will be the TUF-compliant ID. The Store takes care of extensions.
privKeyFilename := filepath.Join(gun, string(kID))
privKeyStore.Add(privKeyFilename, trustmanager.KeyToPEM(keyBytes))
return key, cert, nil
}
示例11: 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
}
示例12: generateCertAndKey
func generateCertAndKey(t *testing.T, tempDir string) (string, string) {
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal("Unable to generate RSA key", err.Error())
}
keyBytes := x509.MarshalPKCS1PrivateKey(rsaKey)
keyOut, err := os.Create(filepath.Join(tempDir, "key"))
if err != nil {
t.Fatal("Unable to create file to write key to", err.Error())
}
defer keyOut.Close()
if err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes}); err != nil {
t.Fatal("Unable to write key to file", err.Error())
}
certOut, err := os.Create(filepath.Join(tempDir, "cert"))
if err != nil {
t.Fatal("Unable to create file to write cert to", err.Error())
}
defer certOut.Close()
generateCertificate(t, rsaKey, certOut)
return keyOut.Name(), certOut.Name()
}
示例13: createTLSConfig
func createTLSConfig(host string) (certPEMBlock, keyPEMBlock []byte, err error) {
now := time.Now()
tpl := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0),
Subject: pkix.Name{CommonName: host},
NotBefore: now.Add(-24 * time.Hour).UTC(),
NotAfter: now.AddDate(1, 0, 0).UTC(),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
MaxPathLen: 1,
IsCA: true,
SubjectKeyId: []byte{1, 2, 3, 4},
Version: 2,
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return
}
der, err := x509.CreateCertificate(rand.Reader, &tpl, &tpl, &key.PublicKey, key)
if err != nil {
return
}
certPEMBlock = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
keyPEMBlock = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
return
}
示例14: getCertificate
func getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
fmt.Printf("getCertificate(%#v)", clientHello)
// name := clientHello.ServerName
name := "www.gov.cn"
glog.Infof("Generating RootCA for %s", name)
template := x509.Certificate{
IsCA: true,
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{name},
},
NotBefore: time.Now().Add(-time.Duration(5 * time.Minute)),
NotAfter: time.Now().Add(180 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
priv, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, err
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, err
}
certPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
keyPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
return &cert, err
}
示例15: GenerateCACertificate
// GenerateCACertificate generates a new certificate authority from the specified org
// and bit size and returns the certificate and key as []byte, []byte
func GenerateCACertificate(org string, bits int) ([]byte, []byte, error) {
template, err := newCertificate(org)
if err != nil {
return nil, nil, err
}
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
template.KeyUsage |= x509.KeyUsageKeyEncipherment
template.KeyUsage |= x509.KeyUsageKeyAgreement
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, err
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, err
}
var certOut bytes.Buffer
var keyOut bytes.Buffer
pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(&keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return certOut.Bytes(), keyOut.Bytes(), nil
}