cacert-gosigner/cmd/signer/main_test.go

97 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"testing"
"time"
"github.com/ThalesIgnite/crypto11"
)
const defaultPkcs11Module = "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so"
func TestStart(t *testing.T) {
pkcs11Module, found := os.LookupEnv("PKCS11_LIB")
if !found {
pkcs11Module = defaultPkcs11Module
}
p11Context, err := crypto11.Configure(&crypto11.Config{
Path: pkcs11Module,
TokenLabel: "localhsm",
Pin: "123456",
})
if err != nil {
t.Fatalf("could not configure PKCS#11 library: %v", err)
}
defer func(p11Context *crypto11.Context) {
err := p11Context.Close()
if err != nil {
t.Errorf("could not close PKCS#11 library context: %v", err)
}
}(p11Context)
pair, err := p11Context.FindKeyPair(nil, []byte("rootkey2022"))
if err != nil {
t.Fatalf("could not find requested key pair: %v", err)
}
serial, err := randomSerialNumber()
if err != nil {
t.Fatal(err)
}
notBefore := time.Now()
notAfter := notBefore.AddDate(20, 0, 0)
certTemplate := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
Country: []string{"CH"},
Organization: []string{"CAcert Inc."},
Locality: []string{"Genève"},
StreetAddress: []string{"Clos Belmont 2"},
PostalCode: []string{"1208"},
CommonName: "CAcert ECC Root 2022",
},
NotBefore: notBefore,
NotAfter: notAfter,
MaxPathLen: 0,
MaxPathLenZero: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCRLSign | x509.KeyUsageCertSign,
IsCA: true,
SignatureAlgorithm: x509.ECDSAWithSHA256,
}
certificate, err := x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, pair.Public(), pair)
if err != nil {
t.Fatalf("could not create root certificate: %v", err)
}
certBlock := &pem.Block{
Type: "CERTIFICATE",
Bytes: certificate,
}
err = os.WriteFile("/tmp/test.pem", pem.EncodeToMemory(certBlock), 0o600)
if err != nil {
t.Errorf("could not write certificate: %v", err)
}
}
func randomSerialNumber() (*big.Int, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, fmt.Errorf("could not generate serial number: %w", err)
}
return serialNumber, nil
}