本文整理汇总了Golang中crypto/x509.MarshalPKCS1PrivateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang MarshalPKCS1PrivateKey函数的具体用法?Golang MarshalPKCS1PrivateKey怎么用?Golang MarshalPKCS1PrivateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MarshalPKCS1PrivateKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:sjn1978,项目名称:go-fuzz,代码行数:28,代码来源:main.go
示例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
}
开发者ID:theckman,项目名称:goiardi,代码行数:33,代码来源:chefcrypto.go
示例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
}
开发者ID:boumenot,项目名称:packer,代码行数:36,代码来源:pkcs8.go
示例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
}
开发者ID:eric-hawthorne,项目名称:relish,代码行数:38,代码来源:crypto_util.go
示例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
}
开发者ID:hashicorp,项目名称:terraform,代码行数:34,代码来源:resource_profitbricks_server.go
示例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()
}
开发者ID:yexiaoming20140413,项目名称:fabio,代码行数:33,代码来源:source_test.go
示例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
}
开发者ID:luisfurquim,项目名称:stonelizard,代码行数:60,代码来源:gencert.go
示例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
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:65,代码来源:crypto.go
示例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
}
开发者ID:mmtauber,项目名称:pollendina,代码行数:34,代码来源:client.go
示例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
}
开发者ID:progrium,项目名称:notary,代码行数:34,代码来源:cli_crypto_service.go
示例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
}
开发者ID:d4l3k,项目名称:upass,代码行数:33,代码来源:crypto.go
示例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()
}
开发者ID:RomainVabre,项目名称:origin,代码行数:29,代码来源:config_test.go
示例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
}
开发者ID:projectarkc,项目名称:psiphon,代码行数:26,代码来源:meek-server.go
示例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
}
开发者ID:snowink,项目名称:goproxy,代码行数:35,代码来源:vps.go
示例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
}
开发者ID:XuesongYang,项目名称:shipyard,代码行数:31,代码来源:tlsutils.go
示例16: RsaGenKey
// Gen RSA key pair
func RsaGenKey(filePath string, bits int) error {
if !IsDirExist(filePath) {
os.Mkdir(filePath, 0700)
}
privPath := filepath.Join(filePath, "private.pem")
pubfPath := filepath.Join(filePath, "public.pem")
if IsFileExist(privPath) || IsFileExist(pubfPath) {
log.Println("Error: files already exist at:", filePath)
return errors.New("RSA key files already exist")
}
// Gen private key
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
file, err := os.Create(privPath)
if err != nil {
log.Println("Error: create ", privPath, " failed")
return err
}
defer file.Close()
err = pem.Encode(file, block)
if err != nil {
return err
}
file.Chmod(0400)
// Gen public key
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
file, err = os.Create(pubfPath)
if err != nil {
log.Println("Error: create ", pubfPath, " failed")
return err
}
defer file.Close()
err = pem.Encode(file, block)
if err != nil {
return err
}
file.Chmod(0400)
return nil
}
开发者ID:st2py,项目名称:bitcrypt,代码行数:61,代码来源:ut_rsa.go
示例17: generateSshKeyUsingGo
func generateSshKeyUsingGo() (string, string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
return "", "", err
}
fmt.Printf("----> creating ssh private key using Golang\n")
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyDer,
}
privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock))
fmt.Printf("----> creating ssh public key using Golang\n")
publicKey := privateKey.PublicKey
publicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
return "", "", err
}
publicKeyBlock := pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))
return privateKeyPem, publicKeyPem, nil
}
开发者ID:digideskweb,项目名称:bosh-softlayer-cpi,代码行数:32,代码来源:test_helpers.go
示例18: generateFromTemplate
// generateFromTemplate generates a certificate from the given template and signed by
// the given parent, storing the results in a certificate and key file.
func generateFromTemplate(certFile, keyFile string, template, parent *x509.Certificate, key crypto.PrivateKey, parentKey crypto.PrivateKey) error {
derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, key.(crypto.Signer).Public(), parentKey)
if err != nil {
return err
}
certOut, err := os.Create(certFile)
if err != nil {
return err
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
switch v := key.(type) {
case *rsa.PrivateKey:
keyBytes := x509.MarshalPKCS1PrivateKey(v)
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes})
case *ecdsa.PrivateKey:
keyBytes, err := x509.MarshalECPrivateKey(v)
if err != nil {
return err
}
pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes})
default:
return fmt.Errorf("Unsupport private key type: %#v", key)
}
return nil
}
开发者ID:PabloSajnovsky,项目名称:quicktls,代码行数:37,代码来源:main.go
示例19: 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)
}
}
}
开发者ID:RadioTerminal,项目名称:podcaster,代码行数:35,代码来源:jwt.go
示例20: TestWebIDRSAAuth
func TestWebIDRSAAuth(t *testing.T) {
request, err := http.NewRequest("GET", testServer.URL+aclDir+"abc", nil)
assert.NoError(t, err)
response, err := httpClient.Do(request)
assert.NoError(t, err)
assert.Equal(t, 401, response.StatusCode)
wwwAuth := response.Header.Get("WWW-Authenticate")
assert.NotEmpty(t, wwwAuth)
p, _ := ParseDigestAuthenticateHeader(wwwAuth)
// Load private key
pKey := x509.MarshalPKCS1PrivateKey(user1k)
keyBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: pKey,
})
signer, err := ParseRSAPrivatePEMKey(keyBytes)
assert.NoError(t, err)
claim := sha1.Sum([]byte(p.Source + user1 + p.Nonce))
signed, err := signer.Sign(claim[:])
assert.NoError(t, err)
b64Sig := base64.StdEncoding.EncodeToString(signed)
assert.NotEmpty(t, b64Sig)
authHeader := `WebID-RSA source="` + p.Source + `", username="` + user1 + `", nonce="` + p.Nonce + `", sig="` + b64Sig + `"`
request, err = http.NewRequest("GET", testServer.URL+aclDir+"abc", nil)
request.Header.Add("Authorization", authHeader)
assert.NoError(t, err)
response, err = httpClient.Do(request)
assert.NoError(t, err)
assert.Equal(t, 200, response.StatusCode)
}
开发者ID:WebCivics,项目名称:gold,代码行数:35,代码来源:auth_test.go
注:本文中的crypto/x509.MarshalPKCS1PrivateKey函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论