1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| package sm2x
import ( "crypto/rand" "encoding/base64" "encoding/hex" "encoding/pem" "fmt" "github.com/tjfoc/gmsm/sm2" "github.com/tjfoc/gmsm/x509" )
type CertDataFrom int
const ( FromBase64 CertDataFrom = iota FromPEM FromHex )
func GenerateSM2PEMKeyPair() (privateKey, publicKey string, err error) { privateKeyObj, err := sm2.GenerateKey(rand.Reader) if err != nil { return "", "", err }
publicKeyObj := &privateKeyObj.PublicKey
privateKeyBytes, err := x509.MarshalSm2UnecryptedPrivateKey(privateKeyObj) if err != nil { return "", "", err }
privateKeyPEM := pem.EncodeToMemory(&pem.Block{ Type: "SM2 PRIVATE KEY", Bytes: privateKeyBytes, })
publicKeyBytes, err := x509.MarshalSm2PublicKey(publicKeyObj) if err != nil { return "", "", err } publicKeyPEM := pem.EncodeToMemory(&pem.Block{ Type: "SM2 PUBLIC KEY", Bytes: publicKeyBytes, }) return string(privateKeyPEM), string(publicKeyPEM), nil }
func NewSM2PrivateKey(data string, from CertDataFrom) (*sm2.PrivateKey, error) { keyBytes, err := decodeCertData(data, from) if err != nil { return nil, err } return x509.ParsePKCS8UnecryptedPrivateKey(keyBytes) }
func NewSM2PublicKey(data string, from CertDataFrom) (*sm2.PublicKey, error) { keyBytes, err := decodeCertData(data, from) if err != nil { return nil, err } return x509.ParseSm2PublicKey(keyBytes) }
func decodeCertData(data string, from CertDataFrom) ([]byte, error) { var keyBytes []byte var err error
switch from { case FromBase64: keyBytes, err = base64.StdEncoding.DecodeString(data) case FromPEM: block, _ := pem.Decode([]byte(data)) if block == nil { return nil, fmt.Errorf("pem 解码证书失败,请传入正确的 pem 证书内容") } keyBytes = block.Bytes case FromHex: keyBytes, err = hex.DecodeString(data) default: return nil, fmt.Errorf("不支持的证书数据源") }
if err != nil { return nil, fmt.Errorf("解码证书失败: %v", err) }
return keyBytes, nil }
func Encrypt(data []byte, publicKey *sm2.PublicKey) ([]byte, error) { return sm2.Encrypt(publicKey, data, rand.Reader, sm2.C1C3C2) }
func Decrypt(data []byte, privateKey *sm2.PrivateKey) ([]byte, error) { return sm2.Decrypt(privateKey, data, sm2.C1C3C2) }
func Sign(data []byte, privateKey *sm2.PrivateKey) ([]byte, error) { return privateKey.Sign(rand.Reader, data, nil) }
func SignVerify(data []byte, publicKey *sm2.PublicKey, signature []byte) bool { return publicKey.Verify(data, signature) }
|