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 }
// 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 }
// 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 }
/* 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 }
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 }
// 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() }
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 }
// 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("%s@%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 }
// 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 }
//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 }
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 }
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() }
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 }
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 }
// 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 }
// 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 }
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 }
// 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 }
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) } } }
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="******", 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) }
// GenerateCA generates a new certificate authority // and stores the resulting certificate and key file // in the arguments. func GenerateCA(certFile, keyFile string) error { log.Printf("Generating a new certificate authority.") template := newCertificate() template.IsCA = true template.KeyUsage |= x509.KeyUsageCertSign priv, err := rsa.GenerateKey(rand.Reader, RSABITS) if err != nil { return err } derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv) 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 } pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) keyOut.Close() return nil }
func CreatePrivateKey(d *schema.ResourceData, meta interface{}) error { keyAlgoName := d.Get("algorithm").(string) var keyFunc keyAlgo var ok bool if keyFunc, ok = keyAlgos[keyAlgoName]; !ok { return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName) } key, err := keyFunc(d) if err != nil { return err } var keyPemBlock *pem.Block switch k := key.(type) { case *rsa.PrivateKey: keyPemBlock = &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k), } case *ecdsa.PrivateKey: keyBytes, err := x509.MarshalECPrivateKey(k) if err != nil { return fmt.Errorf("error encoding key to PEM: %s", err) } keyPemBlock = &pem.Block{ Type: "EC PRIVATE KEY", Bytes: keyBytes, } default: return fmt.Errorf("unsupported private key type") } keyPem := string(pem.EncodeToMemory(keyPemBlock)) pubKey := publicKey(key) pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey) if err != nil { return fmt.Errorf("failed to marshal public key: %s", err) } pubKeyPemBlock := &pem.Block{ Type: "PUBLIC KEY", Bytes: pubKeyBytes, } d.SetId(hashForState(string((pubKeyBytes)))) d.Set("private_key_pem", keyPem) d.Set("public_key_pem", string(pem.EncodeToMemory(pubKeyPemBlock))) sshPubKey, err := ssh.NewPublicKey(pubKey) if err == nil { // Not all EC types can be SSH keys, so we'll produce this only // if an appropriate type was selected. sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey) d.Set("public_key_openssh", string(sshPubKeyBytes)) } else { d.Set("public_key_openssh", "") } return nil }
func sshkey(bits int) (string, string, string, error) { key, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { return "", "", "", err } private := pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }, ) pub := key.Public() pubkey, err := ssh.NewPublicKey(pub) if err != nil { return "", "", "", err } public := ssh.MarshalAuthorizedKey(pubkey) var fp []string f := []byte(fmt.Sprintf("%x", md5.Sum(pubkey.Marshal()))) for i := 0; i < len(f); i += 2 { fp = append(fp, string(f[i:i+2])) } fingerprint := strings.Join(fp, ":") return string(private), string(public), string(fingerprint), nil }
// newLeaf generates a certificate/key pair suitable for use by a leaf node. func newLeaf(caCertPEM, caKeyPEM string, expiry time.Time, hostnames []string, extKeyUsage []x509.ExtKeyUsage) (certPEM, keyPEM string, err error) { tlsCert, err := tls.X509KeyPair([]byte(caCertPEM), []byte(caKeyPEM)) if err != nil { return "", "", err } if len(tlsCert.Certificate) != 1 { return "", "", fmt.Errorf("more than one certificate for CA") } caCert, err := x509.ParseCertificate(tlsCert.Certificate[0]) if err != nil { return "", "", err } if !caCert.BasicConstraintsValid || !caCert.IsCA { return "", "", fmt.Errorf("CA certificate is not a valid CA") } caKey, ok := tlsCert.PrivateKey.(*rsa.PrivateKey) if !ok { return "", "", fmt.Errorf("CA private key has unexpected type %T", tlsCert.PrivateKey) } key, err := rsa.GenerateKey(rand.Reader, KeyBits) if err != nil { return "", "", fmt.Errorf("cannot generate key: %v", err) } now := time.Now() template := &x509.Certificate{ SerialNumber: new(big.Int), Subject: pkix.Name{ // This won't match host names with dots. The hostname // is hardcoded when connecting to avoid the issue. CommonName: "*", Organization: []string{"juju"}, }, NotBefore: now.UTC().AddDate(0, 0, -7), NotAfter: expiry.UTC(), SubjectKeyId: bigIntHash(key.N), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement, ExtKeyUsage: extKeyUsage, } for _, hostname := range hostnames { if ip := net.ParseIP(hostname); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, hostname) } } certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, &key.PublicKey, caKey) if err != nil { return "", "", err } certPEMData := pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: certDER, }) keyPEMData := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }) return string(certPEMData), string(keyPEMData), nil }
// GenerateKeys generates private and public RSA keys func GenerateKeys(bits int) (string, string) { priv, _ := rsa.GenerateKey(rand.Reader, bits) // Get der format. priv_der []byte privDer := x509.MarshalPKCS1PrivateKey(priv) privBlk := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privDer, } // Resultant private key in PEM format. privPem := string(pem.EncodeToMemory(&privBlk)) // Public Key generation pub := priv.PublicKey pubDer, _ := x509.MarshalPKIXPublicKey(&pub) pubBlk := pem.Block{ Type: "PUBLIC KEY", Headers: nil, Bytes: pubDer, } // Resultant public key in PEM format. pubPem := string(pem.EncodeToMemory(&pubBlk)) return privPem, pubPem }
// NewCA generates a CA certificate/key pair suitable for signing server // keys for an environment with the given name. func NewCA(envName string, expiry time.Time) (certPEM, keyPEM string, err error) { key, err := rsa.GenerateKey(rand.Reader, KeyBits) if err != nil { return "", "", err } now := time.Now() template := &x509.Certificate{ SerialNumber: new(big.Int), Subject: pkix.Name{ CommonName: fmt.Sprintf("juju-generated CA for environment %q", envName), Organization: []string{"juju"}, }, NotBefore: now.UTC().AddDate(0, 0, -7), NotAfter: expiry.UTC(), SubjectKeyId: bigIntHash(key.N), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, IsCA: true, MaxPathLen: 0, // Disallow delegation for now. BasicConstraintsValid: true, } certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) if err != nil { return "", "", fmt.Errorf("cannot create certificate: %v", err) } certPEMData := pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: certDER, }) keyPEMData := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }) return string(certPEMData), string(keyPEMData), nil }
func GenerateKey() (pkPem []byte, pubkPem []byte, pubSSHAK []byte, err error) { pk, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return } pkDer := x509.MarshalPKCS1PrivateKey(pk) pkBlock := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: pkDer, } pkPem = pem.EncodeToMemory(&pkBlock) pubk := pk.PublicKey pubkDer, err := x509.MarshalPKIXPublicKey(&pubk) if err != nil { return } pubkBlock := pem.Block{ Type: "PUBLIC KEY", Headers: nil, Bytes: pubkDer, } pubkPem = pem.EncodeToMemory(&pubkBlock) pubSSH, err := ssh.NewPublicKey(&pubk) if err != nil { return } pubSSHAK = ssh.MarshalAuthorizedKey(pubSSH) return }
func generateSshKeyPair() Keypair { priv, err := rsa.GenerateKey(rand.Reader, 2014) if err != nil { util.Fatalf("Error generating key", err) } // Get der format. priv_der []byte priv_der := x509.MarshalPKCS1PrivateKey(priv) // pem.Block // blk pem.Block priv_blk := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: priv_der, } // Resultant private key in PEM format. // priv_pem string priv_pem := string(pem.EncodeToMemory(&priv_blk)) // Public Key generation sshPublicKey, err := ssh.NewPublicKey(&priv.PublicKey) pubBytes := ssh.MarshalAuthorizedKey(sshPublicKey) return Keypair{ pub: []byte(pubBytes), priv: []byte(priv_pem), } }
func EncodePrivateKeyPEM(key *rsa.PrivateKey) []byte { block := pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), } return pem.EncodeToMemory(&block) }
func generateKeys(c Config) { keyPath := c.KeyDirectory username := c.Username privPath := fmt.Sprintf("%s/privatekey_%s.pem", keyPath, username) pubPath := fmt.Sprintf("%s/publickey_%s.pem", keyPath, username) // generate private key privatekey, err := rsa.GenerateKey(rand.Reader, 1024) checkError(err) // Write Private Key privBytes := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privatekey), }) ioutil.WriteFile(privPath, privBytes, 0600) log.Info("Private Key: ", privPath) fmt.Println(string(privBytes)) // Write Public Key ansipub, err := x509.MarshalPKIXPublicKey(&privatekey.PublicKey) checkError(err) pubBytes := pem.EncodeToMemory(&pem.Block{ Type: "RSA PUBLIC KEY", Bytes: ansipub, }) ioutil.WriteFile(pubPath, pubBytes, 0644) log.Info("Public Key: ", pubPath) fmt.Println(string(pubBytes)) }