func (a *AllowedPublicKey) PublicKeyEquals(otherPubKey *rsa.PublicKey) (bool, error) { thisBytes, err := x509.MarshalPKIXPublicKey(a.PublicKey) if err != nil { return false, err } otherBytes, err := x509.MarshalPKIXPublicKey(otherPubKey) if err != nil { return false, err } return bytes.Equal(thisBytes, otherBytes), nil }
// PublicKeysEqual determines whether two public keys have the same marshalled // bytes as one another func PublicKeysEqual(a, b interface{}) (bool, error) { if a == nil || b == nil { return false, errors.New("One or more nil arguments to PublicKeysEqual") } aBytes, err := x509.MarshalPKIXPublicKey(a) if err != nil { return false, err } bBytes, err := x509.MarshalPKIXPublicKey(b) if err != nil { return false, err } return bytes.Compare(aBytes, bBytes) == 0, nil }
func PKPSHA256Hash(cert *x509.Certificate) string { h := sha256.New() switch pub := cert.PublicKey.(type) { case *rsa.PublicKey: der, _ := x509.MarshalPKIXPublicKey(pub) h.Write(der) case *dsa.PublicKey: der, _ := x509.MarshalPKIXPublicKey(pub) h.Write(der) case *ecdsa.PublicKey: der, _ := x509.MarshalPKIXPublicKey(pub) h.Write(der) } return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
func TestLogCache(t *testing.T) { cache := logCache{ logs: make(map[string]*Log), } // Adding a log with an invalid base64 public key should error _, err := cache.AddLog("www.test.com", "1234") test.AssertError(t, err, "AddLog() with invalid base64 pk didn't error") // Adding a log with an invalid URI should error _, err = cache.AddLog(":", "") test.AssertError(t, err, "AddLog() with an invalid log URI didn't error") // Create one keypair & base 64 public key k1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k1") der1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey) test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der1) failed") k1b64 := base64.StdEncoding.EncodeToString(der1) // Create a second keypair & base64 public key k2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k2") der2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey) test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der2) failed") k2b64 := base64.StdEncoding.EncodeToString(der2) // Adding the first log should not produce an error l1, err := cache.AddLog("http://log.one.example.com", k1b64) test.AssertNotError(t, err, "cache.AddLog() failed for log 1") test.AssertEquals(t, cache.Len(), 1) test.AssertEquals(t, l1.uri, "http://log.one.example.com") test.AssertEquals(t, l1.logID, k1b64) // Adding it again should not produce any errors, or increase the Len() l1, err = cache.AddLog("http://log.one.example.com", k1b64) test.AssertNotError(t, err, "cache.AddLog() failed for second add of log 1") test.AssertEquals(t, cache.Len(), 1) test.AssertEquals(t, l1.uri, "http://log.one.example.com") test.AssertEquals(t, l1.logID, k1b64) // Adding a second log should not error and should increase the Len() l2, err := cache.AddLog("http://log.two.example.com", k2b64) test.AssertNotError(t, err, "cache.AddLog() failed for log 2") test.AssertEquals(t, cache.Len(), 2) test.AssertEquals(t, l2.uri, "http://log.two.example.com") test.AssertEquals(t, l2.logID, k2b64) }
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 }
func main() { cert, err := tls.LoadX509KeyPair("C:\\Users\\Marcelle\\git\\huuzlee\\go\\AA_NET\\go-ssl\\certs\\server.pem", "certs/server.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } config := tls.Config{Certificates: []tls.Certificate{cert}} config.Rand = rand.Reader service := "0.0.0.0:8000" listener, err := tls.Listen("tcp", service, &config) if err != nil { log.Fatalf("server: listen: %s", err) } log.Print("server: listening") for { conn, err := listener.Accept() if err != nil { log.Printf("server: accept: %s", err) break } defer conn.Close() log.Printf("server: accepted from %s", conn.RemoteAddr()) tlscon, ok := conn.(*tls.Conn) if ok { log.Print("ok=true") state := tlscon.ConnectionState() for _, v := range state.PeerCertificates { log.Print(x509.MarshalPKIXPublicKey(v.PublicKey)) } } go handleClient(conn) } }
// Implements the h0tb0x transfer protocol func (this *PublicIdentity) Encode(stream io.Writer) error { data, err := x509.MarshalPKIXPublicKey(this.key) if err != nil { return err } return transfer.Encode(stream, data) }
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 }
// 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 }
// KeyExchange marshals a RSA Public Key in ASN.1 format as defined by x.509 // (serialises a public key to DER-encoded PKIX format). See crypto/x509: // x509.MarshalPKIXPublicKey. func KeyExchange(pub *rsa.PublicKey) []byte { asn1, err := x509.MarshalPKIXPublicKey(pub) if err != nil { return nil } return asn1 }
// PublicKeyToEncryptedPEM converts a public key to encrypted pem func PublicKeyToEncryptedPEM(publicKey interface{}, pwd []byte) ([]byte, error) { switch x := publicKey.(type) { case *ecdsa.PublicKey: raw, err := x509.MarshalPKIXPublicKey(x) if err != nil { return nil, err } block, err := x509.EncryptPEMBlock( rand.Reader, "ECDSA PUBLIC KEY", raw, pwd, x509.PEMCipherAES256) if err != nil { return nil, err } return pem.EncodeToMemory(block), nil default: return nil, ErrInvalidKey } }
// 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 }
func (ca *CA) createCAKeyPair(name string) *ecdsa.PrivateKey { caLogger.Debug("Creating CA key pair.") curve := primitives.GetDefaultCurve() priv, err := ecdsa.GenerateKey(curve, rand.Reader) if err == nil { raw, _ := x509.MarshalECPrivateKey(priv) cooked := pem.EncodeToMemory( &pem.Block{ Type: "ECDSA PRIVATE KEY", Bytes: raw, }) err = ioutil.WriteFile(ca.path+"/"+name+".priv", cooked, 0644) if err != nil { caLogger.Panic(err) } raw, _ = x509.MarshalPKIXPublicKey(&priv.PublicKey) cooked = pem.EncodeToMemory( &pem.Block{ Type: "ECDSA PUBLIC KEY", Bytes: raw, }) err = ioutil.WriteFile(ca.path+"/"+name+".pub", cooked, 0644) if err != nil { caLogger.Panic(err) } } if err != nil { caLogger.Panic(err) } return priv }
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 main() { cert, err := tls.LoadX509KeyPair("../certs/CARoot.crt", "../certs/CARoot.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } config := tls.Config{Certificates: []tls.Certificate{cert}} config.Rand = rand.Reader service := "0.0.0.0:9999" listener, err := tls.Listen("tcp", service, &config) if err != nil { log.Fatalf("server: listen: %s", err) } log.Print("server: listening") for { conn, err := listener.Accept() if err != nil { log.Printf("server: accept: %s", err) break } defer conn.Close() log.Printf("server: accepted from %s", conn.RemoteAddr()) tlscon, ok := conn.(*tls.Conn) if ok { log.Print("ok=true") state := tlscon.ConnectionState() for _, v := range state.PeerCertificates { log.Print(x509.MarshalPKIXPublicKey(v.PublicKey)) } } handleClient(conn) } }
func NewServer(motd *string, maxPlayers *uint16, syncMaxPlayers *bool, authenticate *bool, router Router, localizer Localizer, connect *connect.ProxyConnect) (this *Server, err error) { this = new(Server) this.SessionRegistry = NewSessionRegistry() this.motd = motd this.maxPlayers = maxPlayers this.syncMaxPlayers = syncMaxPlayers this.authenticate = authenticate this.router = router this.localizer = localizer this.connect = connect this.privateKey, err = rsa.GenerateKey(cryptoRand.Reader, 2048) if err != nil { return } this.publicKey, err = x509.MarshalPKIXPublicKey(&this.privateKey.PublicKey) if err != nil { return } connect.OnRedirect(func(serverName string, player string) { session := this.SessionRegistry.GetByName(player) if session == nil { return } server := connect.Server(serverName) if server == nil { return } session.Redirect(server) }) return }
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) } } }
// NewTemplate returns a new base *x509.Certificate. func NewTemplate(org, host string, start, end time.Time, pub interface{}) (*x509.Certificate, error) { pkixPub, err := x509.MarshalPKIXPublicKey(pub) if err != nil { return nil, err } h := sha1.New() h.Write(pkixPub) keyID := h.Sum(nil) serial, err := rand.Int(rand.Reader, MaxSerialNumber) if err != nil { return nil, err } return &x509.Certificate{ SerialNumber: serial, Subject: pkix.Name{ CommonName: host, Organization: []string{org}, }, SubjectKeyId: keyID, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, DNSNames: []string{host}, NotBefore: start, NotAfter: end, }, nil }
func TestECDSAVerifierOtherCurves(t *testing.T) { curves := []elliptic.Curve{elliptic.P256(), elliptic.P384(), elliptic.P521()} for _, curve := range curves { ecdsaPrivKey, err := ecdsa.GenerateKey(curve, rand.Reader) // Get a DER-encoded representation of the PublicKey ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey) assert.NoError(t, err, "failed to marshal public key") // Get a DER-encoded representation of the PrivateKey ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey) assert.NoError(t, err, "failed to marshal private key") testECDSAPubKey := data.NewECDSAPublicKey(ecdsaPubBytes) testECDSAKey, err := data.NewECDSAPrivateKey(testECDSAPubKey, ecdsaPrivKeyBytes) assert.NoError(t, err, "failed to read private key") // Sign some data using ECDSA message := []byte("test data for signing") hashed := sha256.Sum256(message) signedData, err := ecdsaSign(testECDSAKey, hashed[:]) assert.NoError(t, err) // Create and call Verify on the verifier ecdsaVerifier := ECDSAVerifier{} err = ecdsaVerifier.Verify(testECDSAKey, signedData, message) assert.NoError(t, err, "expecting success but got error while verifying data using ECDSA") // Make sure an invalid signature fails verification signedData[0]++ err = ecdsaVerifier.Verify(testECDSAKey, signedData, message) assert.Error(t, err, "expecting error but got success while verifying data using ECDSA") } }
func pubkeyDump(w indent.Writer, cert *x509.Certificate) { switch cert.PublicKeyAlgorithm { case x509.ECDSA: w.Printf("Public Key Algorithm: %s\n", w.Bold("ECDSA")) pub, ok := cert.PublicKey.(*ecdsa.PublicKey) if !ok { w.Println(w.Bold("[unrecognizable]")) return } w.Headerf("Public Key: (%s)\n", w.Bold("%d bits", pub.Params().BitSize)) w.PrintHex(elliptic.Marshal(pub.Curve, pub.X, pub.Y)) w.Dedent() w.Printf("Curve: %s\n", EcdsaCurveName[pub.Curve]) return case x509.RSA: w.Printf("Public Key Algorithm: RSA\n") case x509.DSA: w.Printf("Public Key Algorithm: DSA\n") default: w.Printf("Public Key Algorithm: Unknown (type %d)\n", cert.PublicKeyAlgorithm) } b, err := x509.MarshalPKIXPublicKey(cert.PublicKey) w.Headerf("Public Key:\n") if err != nil { w.Printf("[unrecognizable]\n") } else { w.PrintHex(b) } w.Dedent() }
func runClient() { cert, err := tls.LoadX509KeyPair(clientTLSCert, clientTLSKey) if err != nil { log.Fatalf("client: error loading keys: %s", err) } tlsconf := &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} conn, err := tls.Dial("tcp", addr, tlsconf) if err != nil { log.Fatalf("client: dial: %s", err) } defer conn.Close() log.Println("client: connected to: ", conn.RemoteAddr()) state := conn.ConnectionState() for _, v := range state.PeerCertificates { fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey)) fmt.Println(v.Subject) } log.Println("client: handshake: ", state.HandshakeComplete) log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual) message := "Hello\n" n, err := io.WriteString(conn, message) if err != nil { log.Fatalf("client: write: %s", err) } log.Printf("client: wrote %q (%d bytes)", message, n) reply := make([]byte, 256) n, err = conn.Read(reply) log.Printf("client: read %q (%d bytes)", string(reply[:n]), n) log.Print("client: exiting") }
func main() { cert, err := tls.LoadX509KeyPair("C:\\Users\\Marcelle\\git\\huuzlee\\go\\AA_NET\\go-ssl\\certs\\client.pem", "certs/client.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} conn, err := tls.Dial("tcp", "127.0.0.1:8000", &config) if err != nil { log.Fatalf("client: dial: %s", err) } defer conn.Close() log.Println("client: connected to: ", conn.RemoteAddr()) state := conn.ConnectionState() for _, v := range state.PeerCertificates { fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey)) fmt.Println(v.Subject) } log.Println("client: handshake: ", state.HandshakeComplete) log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual) message := "Hello\n" n, err := io.WriteString(conn, message) if err != nil { log.Fatalf("client: write: %s", err) } log.Printf("client: wrote %q (%d bytes)", message, n) reply := make([]byte, 256) n, err = conn.Read(reply) log.Printf("client: read %q (%d bytes)", string(reply[:n]), n) log.Print("client: exiting") }
// NewConfig creates a MITM config using the CA certificate and // private key to generate on-the-fly certificates. func NewConfig(ca *x509.Certificate, privateKey interface{}) (*Config, error) { roots := x509.NewCertPool() roots.AddCert(ca) priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, err } pub := priv.Public() // Subject Key Identifier support for end entity certificate. // https://www.ietf.org/rfc/rfc3280.txt (section 4.2.1.2) pkixpub, err := x509.MarshalPKIXPublicKey(pub) if err != nil { return nil, err } h := sha1.New() h.Write(pkixpub) keyID := h.Sum(nil) return &Config{ ca: ca, capriv: privateKey, priv: priv, keyID: keyID, validity: time.Hour, org: "Martian Proxy", certs: make(map[string]*tls.Certificate), roots: roots, }, 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 }
/* 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 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)) }
func MakeTPMPrin(verifier *rsa.PublicKey, pcrNums []int, pcrVals [][]byte) (auth.Prin, error) { aik, err := x509.MarshalPKIXPublicKey(verifier) if err != nil { return auth.Prin{}, err } name := auth.NewTPMPrin(aik) asp := auth.PrinExt{ Name: "PCRs", Arg: make([]auth.Term, 2), } var pcrNumStrs []string for _, v := range pcrNums { pcrNumStrs = append(pcrNumStrs, strconv.Itoa(v)) } asp.Arg[0] = auth.Str(strings.Join(pcrNumStrs, ",")) var pcrValStrs []string for _, p := range pcrVals { pcrValStrs = append(pcrValStrs, hex.EncodeToString(p)) } asp.Arg[1] = auth.Str(strings.Join(pcrValStrs, ",")) // The PCRs are the first extension of the name. name.Ext = []auth.PrinExt{asp} return name, nil }
// Local returns a certificate that may be used to establish a TLS // connection to the specified instance. func (s *RemoteCertSource) Local(instance string) (ret tls.Certificate, err error) { var ( p, _, n = splitName(instance) url = fmt.Sprintf("%s/instances/%s/createEphemeral", p, n) data struct { Cert string } ) pkix, err := x509.MarshalPKIXPublicKey(&s.key.PublicKey) if err != nil { return ret, err } var request = struct { Key string `json:"public_key"` }{ string(pem.EncodeToMemory(&pem.Block{Bytes: pkix, Type: "RSA PUBLIC KEY"})), } if err := s.jsonReq("POST", url, request, &data); err != nil { return ret, err } c, err := parseCert(data.Cert) if err != nil { return ret, fmt.Errorf("coudln't parse ephemeral certificate for instance %q: %v", instance, err) } return tls.Certificate{ Certificate: [][]byte{c.Raw}, PrivateKey: s.key, Leaf: c, }, nil }
// GenerateKeys returns a new key pair, with the private and public key // encoded in PEM format. func GenerateKeys() (privKey []byte, pubKey []byte, err error) { // Generate a new key pair key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, nil, err } // Marshal the private key bs, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, nil, err } // Encode it in PEM format privKey = pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: bs, }) // Marshal the public key bs, err = x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, nil, err } // Encode it in PEM format pubKey = pem.EncodeToMemory(&pem.Block{ Type: "EC PUBLIC KEY", Bytes: bs, }) return }
func openTLSClient(ipPort string) (*tls.Conn, error) { // Note this loads standard x509 certificates, test keys can be // generated with makecert.sh cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } // InsecureSkipVerify required for unsigned certs with Go1 and later. config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} conn, err := tls.Dial("tcp", ipPort, &config) if err != nil { log.Fatalf("client: dial: %s", err) } log.Println("client: connected to: ", conn.RemoteAddr()) // This shows the public key of the server, we will accept any key, but // we could terminate the connection based on the public key if desired. state := conn.ConnectionState() for _, v := range state.PeerCertificates { fmt.Println("Client: Server public key is:") fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey)) } // Lets verify behind the doubt that both ends of the connection // have completed the handshake and negotiated a SSL connection log.Println("client: handshake: ", state.HandshakeComplete) log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual) // All TLS handling has completed, now to pass the connection off to // go-rpcgen/protobuf/AddService return conn, err }