sm2,smx509: add encoding paths for SM2 ecdh keys

This commit is contained in:
Sun Yimin 2022-11-21 10:09:57 +08:00 committed by GitHub
parent 984913e228
commit f1993bc41a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -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()

View File

@ -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")
}
}