generate_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cert
  2. import (
  3. "crypto/x509"
  4. "crypto/x509/pkix"
  5. "encoding/pem"
  6. "testing"
  7. )
  8. func TestCreateCert(t *testing.T) {
  9. dnsName := "ehang.io"
  10. g := NewX509Generator(pkix.Name{
  11. Country: []string{"CN"},
  12. Organization: []string{"ehang.io"},
  13. OrganizationalUnit: []string{"nps"},
  14. Province: []string{"Beijing"},
  15. CommonName: "nps",
  16. Locality: []string{"Beijing"},
  17. })
  18. // generate root ca
  19. rootCa, rootKey, err := g.CreateRootCa()
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. err = g.InitRootCa(rootCa, rootKey)
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. // generate npc cert
  28. clientCa, _, err := g.CreateCert(dnsName)
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. // verify npc cert by root cert
  33. roots := x509.NewCertPool()
  34. ok := roots.AppendCertsFromPEM(rootCa)
  35. if !ok {
  36. panic("failed to parse root certificate")
  37. }
  38. block, _ := pem.Decode(clientCa)
  39. if block == nil {
  40. t.Fatal("failed to parse certificate PEM")
  41. }
  42. cert, err := x509.ParseCertificate(block.Bytes)
  43. if err != nil {
  44. t.Fatal("failed to parse certificate: " + err.Error())
  45. }
  46. opts := x509.VerifyOptions{
  47. Roots: roots,
  48. DNSName: dnsName,
  49. Intermediates: x509.NewCertPool(),
  50. }
  51. if _, err := cert.Verify(opts); err != nil {
  52. t.Fatal("failed to verify certificate: " + err.Error())
  53. }
  54. }