github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/secrets/keystore.go (about)

     1  package secrets
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"crypto/x509/pkix"
     8  	"io"
     9  	"math"
    10  	"math/big"
    11  	"time"
    12  
    13  	"github.com/pavlo-v-chernykh/keystore-go/v4"
    14  )
    15  
    16  func GenerateKeystore(
    17  	storepass,
    18  	keypass,
    19  	alias,
    20  	cname string,
    21  
    22  	validity time.Duration,
    23  	bits uint32,
    24  
    25  	writer io.Writer,
    26  ) error {
    27  	// Generate private key
    28  	key, err := rsa.GenerateKey(rand.Reader, int(bits))
    29  	if err != nil {
    30  		return err
    31  	}
    32  
    33  	rawKey, err := x509.MarshalPKCS8PrivateKey(key)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	// Generate certificate
    39  	serialNumber, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	now := time.Now()
    45  	tpl := &x509.Certificate{
    46  		SerialNumber: serialNumber,
    47  		NotBefore:    now,
    48  		NotAfter:     now.Add(validity),
    49  		Subject: pkix.Name{
    50  			CommonName: cname,
    51  		},
    52  		Issuer: pkix.Name{
    53  			CommonName: cname,
    54  		},
    55  	}
    56  
    57  	cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	// Generate & write keystore
    63  	ks := keystore.New()
    64  
    65  	if err := ks.SetPrivateKeyEntry(
    66  		alias,
    67  		keystore.PrivateKeyEntry{
    68  			CreationTime: time.Now(),
    69  			PrivateKey:   rawKey,
    70  			CertificateChain: []keystore.Certificate{
    71  				{
    72  					Type:    "X509",
    73  					Content: cert,
    74  				},
    75  			},
    76  		},
    77  		[]byte(keypass),
    78  	); err != nil {
    79  		return err
    80  	}
    81  
    82  	return ks.Store(writer, []byte(storepass))
    83  }