voucher/internal/pkg/cmb/sm2/util/x509.go

39 lines
918 B
Go

package util
import (
"codeup.aliyun.com/lsxd/backend_deveoper/gmutil/sm2/model"
"crypto/elliptic"
"crypto/x509/pkix"
"encoding/asn1"
"fmt"
"reflect"
)
var (
oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} // I get the SM2 ID through parsing the pem file generated by gmssl
)
// PKIXPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
// in RFC 3280.
type PKIXPublicKey struct {
Algo pkix.AlgorithmIdentifier
BitString asn1.BitString
}
func ParsePublicKey(bytes []byte) (*model.PublicKey, error) {
var pk PKIXPublicKey
if _, err := asn1.Unmarshal(bytes, &pk); err != nil {
return nil, err
}
if !reflect.DeepEqual(pk.Algo.Algorithm, oidSM2) {
return nil, fmt.Errorf("not sm2 elliptic curve")
}
curve := NewP256Sm2()
x, y := elliptic.Unmarshal(curve, pk.BitString.Bytes)
return &model.PublicKey{
Curve: curve,
X: x,
Y: y,
}, nil
}