github.com/kayoticsully/syncthing@v0.8.9-0.20140724133906-c45a2fdc03f8/cmd/syncthing/tls.go (about) 1 // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file). 2 // All rights reserved. Use of this source code is governed by an MIT-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "crypto/rand" 9 "crypto/rsa" 10 "crypto/sha256" 11 "crypto/tls" 12 "crypto/x509" 13 "crypto/x509/pkix" 14 "encoding/binary" 15 "encoding/pem" 16 "math/big" 17 mr "math/rand" 18 "os" 19 "path/filepath" 20 "time" 21 ) 22 23 const ( 24 tlsRSABits = 3072 25 tlsName = "syncthing" 26 ) 27 28 func loadCert(dir string, prefix string) (tls.Certificate, error) { 29 cf := filepath.Join(dir, prefix+"cert.pem") 30 kf := filepath.Join(dir, prefix+"key.pem") 31 return tls.LoadX509KeyPair(cf, kf) 32 } 33 34 func certSeed(bs []byte) int64 { 35 hf := sha256.New() 36 hf.Write(bs) 37 id := hf.Sum(nil) 38 return int64(binary.BigEndian.Uint64(id)) 39 } 40 41 func newCertificate(dir string, prefix string) { 42 l.Infoln("Generating RSA certificate and key...") 43 44 priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits) 45 l.FatalErr(err) 46 47 notBefore := time.Now() 48 notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC) 49 50 template := x509.Certificate{ 51 SerialNumber: new(big.Int).SetInt64(mr.Int63()), 52 Subject: pkix.Name{ 53 CommonName: tlsName, 54 }, 55 NotBefore: notBefore, 56 NotAfter: notAfter, 57 58 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 59 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, 60 BasicConstraintsValid: true, 61 } 62 63 derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) 64 l.FatalErr(err) 65 66 certOut, err := os.Create(filepath.Join(dir, prefix+"cert.pem")) 67 l.FatalErr(err) 68 pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) 69 certOut.Close() 70 l.Okln("Created RSA certificate file") 71 72 keyOut, err := os.OpenFile(filepath.Join(dir, prefix+"key.pem"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) 73 l.FatalErr(err) 74 pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) 75 keyOut.Close() 76 l.Okln("Created RSA key file") 77 }