From f1993bc41a74564c8d4fb122068d239289257d4c Mon Sep 17 00:00:00 2001 From: Sun Yimin Date: Mon, 21 Nov 2022 10:09:57 +0800 Subject: [PATCH] sm2,smx509: add encoding paths for SM2 ecdh keys --- sm2/sm2_test.go | 14 ++++++++++++++ smx509/x509_additional_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/sm2/sm2_test.go b/sm2/sm2_test.go index 35c8d7b..4d7b873 100644 --- a/sm2/sm2_test.go +++ b/sm2/sm2_test.go @@ -424,6 +424,20 @@ func TestCipherASN1WithInvalidBytes(t *testing.T) { } } +func TestPublicKeyToECDH(t *testing.T) { + priv, _ := GenerateKey(rand.Reader) + _, err := PublicKeyToECDH(&priv.PublicKey) + if err != nil { + t.Fatal(err) + } + + p256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + _, err = PublicKeyToECDH(&p256.PublicKey) + if err == nil { + t.Fatal("should be error") + } +} + func BenchmarkGenerateKey_SM2(b *testing.B) { b.ReportAllocs() b.ResetTimer() diff --git a/smx509/x509_additional_test.go b/smx509/x509_additional_test.go index 7b35a4a..43d2b20 100644 --- a/smx509/x509_additional_test.go +++ b/smx509/x509_additional_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" + "github.com/emmansun/gmsm/ecdh" "github.com/emmansun/gmsm/sm2" ) @@ -186,3 +187,29 @@ func parseAndCheckCsr(csrPem []byte) error { } return csr.CheckSignature() } + +func TestMarshalECDHPKIXPublicKey(t *testing.T) { + privKey, err := ecdh.P256().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + result1, err := MarshalPKIXPublicKey(privKey.Public()) + if err != nil { + t.Fatal(err) + } + pubKey, err := ParsePKIXPublicKey(result1) + if err != nil { + t.Fatal(err) + } + sm2PubKey, ok := pubKey.(*ecdsa.PublicKey) + if !ok { + t.Fatal("should be valid sm2 public key") + } + sm2ecdhPub, err := sm2.PublicKeyToECDH(sm2PubKey) + if err != nil { + t.Fatal(err) + } + if !privKey.PublicKey().Equal(sm2ecdhPub) { + t.Fatal("should be same") + } +}