package config import ( "crypto/elliptic" "crypto/x509" "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestPrivateKeyInfo_MarshalJSON(t *testing.T) { testData := []struct { name string pkInfo *PrivateKeyInfo expected string }{ { "RSA", &PrivateKeyInfo{ Algorithm: x509.RSA, RSABits: 3072, }, `{"algorithm":"RSA","rsa-bits":3072}`, }, { "ECDSA", &PrivateKeyInfo{ Algorithm: x509.ECDSA, EccCurve: elliptic.P224(), }, `{"algorithm":"EC","ecc-curve":"P-224"}`, }, } for _, item := range testData { t.Run(item.name, func(t *testing.T) { data, err := json.Marshal(item.pkInfo) if err != nil { t.Fatal(err) } assert.Equal(t, item.expected, string(data)) }) } } func TestPrivateKeyInfo_UnmarshalJSON(t *testing.T) { testData := []struct { name string json string expected *PrivateKeyInfo expectErr bool }{ { "RSA", `{"label":"mykey","algorithm":"RSA","rsa-bits":2048}`, &PrivateKeyInfo{ Algorithm: x509.RSA, RSABits: 2048, }, false, }, { "ECDSA", `{"label":"mykey","algorithm":"EC","ecc-curve":"P-521"}`, &PrivateKeyInfo{ Algorithm: x509.ECDSA, EccCurve: elliptic.P521(), }, false, }, { "no-algorithm", `{"label":"mykey"}`, nil, true, }, { "RSA-no-rsa-bits", `{"label":"mykey","algorithm":"RSA"}`, nil, true, }, { "ECDSA-no-curve", `{"label":"mykey","algorithm":"EC"}`, nil, true, }, } for _, item := range testData { t.Run(item.name, func(t *testing.T) { pkInfo := &PrivateKeyInfo{} err := json.Unmarshal([]byte(item.json), pkInfo) if err != nil { if !item.expectErr { t.Fatal(err) } } if !item.expectErr { assert.Equal(t, item.expected, pkInfo) } }) } } func TestCaCertificateEntry_UnmarshalJSON(t *testing.T) { data := `{ "label":"root", "key-info": { "algorithm":"EC", "ecc-curve":"P-521" }, "certificate-file":"test.crt", "common-name":"My Little Test Root CA" }` entry := CaCertificateEntry{} err := json.Unmarshal([]byte(data), &entry) if err != nil { t.Fatal(err) } assert.Equal(t, CaCertificateEntry{ Label: "root", KeyInfo: &PrivateKeyInfo{ Algorithm: x509.ECDSA, EccCurve: elliptic.P521(), }, CommonName: "My Little Test Root CA", }, entry) }