Golang使用RSA进行公钥加密私钥解密,私钥加密公钥解密的实现
基于 https://github.com/farmerx/gorsa 进行封装优化了如下几点:
公私钥需要提前注册,在并发情况下公私钥匙会混乱
加密机没有进行base64处理,在跨程序传递或存储过程中都避免base64二次封装
传入返回都统一使用string类型避免转换麻烦
获取扩展包:
go get github.com/wenzhenxi/gorsa具体使用:
package mainimport ("log""errors""github.com/wenzhenxi/gorsa")var Pubkey = `-----BEGIN 公钥-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQAB-----END 公钥-----`var Pirvatekey = `-----BEGIN 私钥-----MIIEpAIBAAKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQABAoIBAQCCbxZvHMfvCeg+YUD5+W63dMcq0QPMdLLZPb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xYr+LqQ25/+TGvINjuf6P3fVkHL0U8jOG0IqpPJXO3Vl9B8ewWLcFQVB/nQfmaMa4ChK0QEUe+Mqi++MwgYbRHx1lIOXEfUJO+PXrMekw==-----END 私钥-----`func main() {// 公钥加密私钥解密if err := applyPubEPriD(); err != nil {log.Println(err)}// 公钥解密私钥加密if err := applyPriEPubD(); err != nil {log.Println(err)}}// 公钥加密私钥解密func applyPubEPriD() error {pubenctypt, err := gorsa.PublicEncrypt(`hello world`,Pubkey)if err != nil {return err}pridecrypt, err := gorsa.PriKeyDecrypt(pubenctypt,Pirvatekey)if err != nil {return err}if string(pridecrypt) != `hello world` {return errors.New(`解密失败`)}return nil}// 公钥解密私钥加密func applyPriEPubD() error {prienctypt, err := gorsa.PriKeyEncrypt(`hello world`,Pirvatekey)if err != nil {return err}pubdecrypt, err := gorsa.PublicDecrypt(prienctypt,Pubkey)if err != nil {return err}if string(pubdecrypt) != `hello world` {return errors.New(`解密失败`)}return nil}
评论