package main
import (
"crypto/rand"
"fmt"
"io/ioutil"
"github.com/tjfoc/gmsm/sm2"
)
// 生成公钥私钥并写入文件 // privateKeyPath:私钥路径 // publicKeyPath:公钥路径 // password:用于加密私钥 func WriteKeyPairToFile(privateKeyPath, publicKeyPath string, password []byte) error {
//生成秘钥对
privateKey, err := sm2.GenerateKey(rand.Reader)
if err != nil {
return err
}
privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return err
}
err = ioutil.WriteFile(privateKeyPath, privateKeyBytes, 0600)
if err != nil {
return err
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}
err = ioutil.WriteFile(publicKeyPath, publicKeyBytes, 0644)
if err != nil {
return err
}
return nil
}
// 从文件中读取公钥和私钥 func ReadKeyPairFromFile(privateKeyPath, publicKeyPath string) (*sm2.PrivateKey, *sm2.PublicKey, error) {
privateKeyBytes, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to read private key file: %w",err)
}
privateKeyBlock,err := pem.Decode(privateKeyBytes)
if privateKeyBlock ==nil || privateKeyBlock.Type !="PRIVATE KEY"{
return nil,nil,err
}
privateKey,err:=x509.ParsePKCS8PrivateKey(privatekeyBlock.Bytes)
if privateKey==nil{
return nil,nil,err
}
privateKeySm2, ok := privateKey.(*sm2.PrivateKey)
if !ok {
return nil,nil,errors.New("private key is not SM2 private key")
}
publicKeyBytes, err := ioutil.ReadFile(publicKeyPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to read public key file: %w",err)
}
publicKeyBlock, _:= pem.Decode(publicKeyBytes)
publicKey,err:=x509.ParsePKIXPublicKey(publickeyblock.Bytes)
if publicKey==nil{
return nil,nil,err
}
publicKeySm2, ok := publicKey.(*sm2.PublicKey)
if !ok {
return nil,nil,errors.New("public key is not SM2 public key")
}
return privateKeySm2, publicKeySm2, nil
}
func main() {
err := WriteKeyPairToFile("private.pem", "public.pem", []byte("1234"))
if err != nil {
fmt.Println("秘钥对写入文件失败!")
return
}
privateKey, publicKey, err := ReadKeyPairFromFile("private.pem", "public.pem")
if err != nil {
fmt.Println("读取公钥私钥失败!")
return
}
fileData, err := ioutil.ReadFile("E:/1.mp4")
if err != nil {
fmt.Println("文件读取失败!")
return
}
sigMsg,_ := sm2.Sign(rand.Reader,privatekey,filedata,nil)
ok:=sm2.Verify(pubkey,filedata,sigMsg)
if ok{
fmt.Println("验证成功")
}else{
fmt.Println("验证失败")
}
}
内容由零声教学AI助手提供,问题来源于学员提问