Skip to content

Commit

Permalink
cfca: pkcs12 sm2, supplement test data
Browse files Browse the repository at this point in the history
  • Loading branch information
emmansun authored Dec 16, 2024
1 parent 008b209 commit 0d3a2d2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
6 changes: 4 additions & 2 deletions cfca/pkcs12_sm2.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Package cfca handles cfca issued key and certificate
// Package cfca supports part of CFCA SADK's functions.
package cfca

import (
Expand Down Expand Up @@ -41,6 +41,7 @@ var (
)

// ParseSM2 parses the der data, returns private key and related certificate, it's CFCA private structure.
// This methed is coresponding to CFCA SADK's cfca.sadk.asn1.pkcs.load.
func ParseSM2(password, data []byte) (*sm2.PrivateKey, *smx509.Certificate, error) {
var keys cfcaKeyPairData
if _, err := asn1.Unmarshal(data, &keys); err != nil {
Expand Down Expand Up @@ -74,7 +75,8 @@ func ParseSM2(password, data []byte) (*sm2.PrivateKey, *smx509.Certificate, erro
return prvKey, cert, nil
}

// MarshalSM2 encodes sm2 private key and related certificate to cfca defined format
// MarshalSM2 encodes sm2 private key and related certificate to cfca defined format.
// This methed is coresponding to CFCA SADK's cfca.sadk.asn1.pkcs.CombineSM2Data.
func MarshalSM2(password []byte, key *sm2.PrivateKey, cert *smx509.Certificate) ([]byte, error) {
var err error
var ciphertext []byte
Expand Down
54 changes: 51 additions & 3 deletions cfca/pkcs12_sm2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,57 @@ func parseTestKeyAndCert() (*sm2.PrivateKey, *smx509.Certificate, error) {
}

func TestParseSM2(t *testing.T) {
_, _, err := parseTestKeyAndCert()
if err != nil {
t.Fatal(err)
cases := []struct {
pem string
password []byte
}{
{
v2exKeyPem,
[]byte("123456"),
},
{
`-----BEGIN CFCA KEY-----
MIIDmwIBATBHBgoqgRzPVQYBBAIBBgcqgRzPVQFoBDAjEsMB1LZrH4B5zBJQLh/S3vLTegY5twIU
lKu80vkB3XLfImABwhYVzFkjfJY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IQCV2YwNr90ad1E5mZqzmdkU0E1CWie9K0lsml012slavgIhAM/++u/l1x5cCIPZsCOYrIy2
0N8+aiLInpgEnkw3wQMt
-----END CFCA KEY-----
`,
[]byte("ys123456"),
},
}

for _, c := range cases {
block, _ := pem.Decode([]byte(c.pem))
if block == nil {
t.Fatal("failed to decode PEM block")
}
priv, cert, err := ParseSM2(c.password, block.Bytes)
if err != nil {
t.Fatal(err)
}
if priv == nil {
t.Fatal("failed to parse private key")
}
if cert == nil {
t.Fatal("failed to parse certificate")
}
if !priv.PublicKey.Equal(cert.PublicKey) {
t.Fatal("public key mismatch")
}
}
}

Expand Down

0 comments on commit 0d3a2d2

Please sign in to comment.