ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> ### RSA ~~~ package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "fmt" ) // 私钥生成 //openssl genrsa -out rsa_private_key.pem 1024 var privateKey = []byte(` -----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDKogrjd6Sj/atsQpdbJsvp/s5c0As8edgJ/6ol23aNVzBde9Rk lxBEH1plvKR+5iq8YPwhU5JPYBfO73wlMqQj7hLeQTde1ll8UR0lUkYSrxuZG2NC HDBxOYiqfMBH+PJYQcN9veJa6Y6l9J0yY4/bXRfaaJdnbn/EqMhARHBMcQIDAQAB AoGAHxLOXKeCReummAl2MHI4nv+GIdF9h56ftJjSPM/01CPktNFCdtJ7mha8xBEz oIonT5AH2gx4yVdRD1jGTuX/KYUtj15BRWsZTaPrbOCAvZZq/ZmVGBINI2uzk7Bw wALAdJXhXHNYteTChJOFE62LPbF5/hV9U6Ug/DrqxcMRweECQQD7S/1wJLEJtb57 SvgtL+1+TppFQVEaMdGFdjKE5/IJ/7fFMX36SNZXxt7MwRoVz/ulyAM4II/ddqfC HjSc8p6dAkEAzmzlGc54tHkh6VtaB4xI+cPgNCjuBhckV/ALjmCNRcwuGx0FMnpb 06RjTVA4Owd4r7qiEQvG8mA+4k7wJdjy5QJBAMIVVpAeRn1xWMRwimyb75j1rECA ydqpT2D8gNgVK+J9Fbm/F8UOLD1u4vTQzwy5rWnEqHfY7kPlOHu8SHZPDCECQAkT 3NdPrxswoH8kl0bxslvZc0iX7C+0YNLFKZzvPgctvXFPy2S24Mbj2cISnwZpg7Mm n+3j+LG77cgB9KmVaskCQAjwtwarWuUeuB3D1PBmoA0HXifmUBl8EMHBdqg+4HtK rgIM5CiOS33aa4ZYZTbuCFadFLxWH2QOeCiHRRERTAk= -----END RSA PRIVATE KEY----- `) // 公钥: 根据私钥生成 //openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem var publicKey = []byte(` -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKogrjd6Sj/atsQpdbJsvp/s5c 0As8edgJ/6ol23aNVzBde9RklxBEH1plvKR+5iq8YPwhU5JPYBfO73wlMqQj7hLe QTde1ll8UR0lUkYSrxuZG2NCHDBxOYiqfMBH+PJYQcN9veJa6Y6l9J0yY4/bXRfa aJdnbn/EqMhARHBMcQIDAQAB -----END PUBLIC KEY----- `) func main() { stringVal := "Hello World" fmt.Println("加密前内容: ", stringVal) encryptCode, err := RsaEncrypt([]byte(stringVal)) if err != nil{ fmt.Println(err.Error()) return } fmt.Println("公钥加密后内容: ", base64.StdEncoding.EncodeToString(encryptCode)) decryptCode , err:= RsaDecrypt(encryptCode) if err != nil{ fmt.Println(err.Error()) return } fmt.Println("私钥解密后内容: ", string(decryptCode)) } // 加密 func RsaEncrypt(origData []byte) ([]byte, error) { //解密pem格式的公钥 block, _ := pem.Decode(publicKey) if block == nil { return nil, errors.New("public key error") } // 解析公钥 pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, err } // 类型断言 pub := pubInterface.(*rsa.PublicKey) //加密 return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) } // 解密 func RsaDecrypt(ciphertext []byte) ([]byte, error) { //解密 block, _ := pem.Decode(privateKey) if block == nil { return nil, errors.New("private key error!") } //解析PKCS1格式的私钥 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } // 解密 return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) } ~~~