怎么用 GO 实现 RSA 的私钥加密公钥解密

 我来答
匿名用户
2017-09-22
展开全部
packagemainimport("crypto/rand""crypto/rsa""crypto/x509""encoding/base64""encoding/pem""errors""flag""fmt")vardecryptedstringfuncinit(){flag.StringVar(&decrypted,"d","","加密过的数据")flag.Parse()}funcmain(){vardata[]bytevarerrerrorifdecrypted!=""{data,err=base64.StdEncoding.DecodeString(decrypted)iferr!=nil{panic(err)}}else{data,err=RsaEncrypt([]byte("polaris@studygolang.com"))iferr!=nil{panic(err)}fmt.Println("rsaencryptbase64:"+base64.StdEncoding.EncodeToString(data))}origData,err:=RsaDecrypt(data)iferr!=nil{panic(err)}fmt.Println(string(origData))}//公钥和私钥可以从文件中读取varprivateKey=[]byte(`-----BEGINRSAPRIVATEKEY-----MIICXQIBAAKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQABAoGBAJlNxenTQj6OfCl9FMR2jlMJjtMrtQT9InQEE7m3m7bLHeC+MCJOhmNVBjaMZpthDORdxIZ6oCuOf6Z2+Dl35lntGFh5J7S34UP2BWzF1IyyQfySCNexGNHKT1G1XKQtHmtc2gWWthEg+S6ciIyw2IGrrP2Rke81vYHExPrexf0hAkEA9Izb0MiYsMCB/jemLJB0Lb3Y/B8xjGjQFFBQT7bmwBVjvZWZVpnMnXi9sWGdgUpxsCuAIROXjZ40IRZ2C9EouwJBAOPjPvV8Sgw4vaseOqlJvSq/C/pIFx6RVznDGlc8bRg7SgTPpjHG4G+M3mVgpCX1a/EU1mB+fhiJ2LAZ/pTtY6sCQGaW9NwIWu3DRIVGCSMm0mYh/3X9DAcwLSJoctiODQ1Fq9rreDE5QfpJnaJdJfsIJNtX1F+L3YceeBXtW0Ynz2MCQBI89KP274Is5FkWkUFNKnuKUK4WKOuEXEO+LpR+vIhs7k6WQ8nGDd4/mujoJBr5mkrwDPwqA3N5TMNDQVGv8gMC CaKGJgWYgvo3/milFfImbp+m7/Y3vCptarldXrYQWOAQjxwc71ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O-----ENDRSAPRIVATEKEY-----`)varpublicKey=[]byte(`-----BEGINPUBLICKEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQAB-----ENDPUBLICKEY-----`)//加密funcRsaEncrypt(origData[]byte)([]byte,error){block,_:=pem.Decode(publicKey)ifblock==nil{returnnil,errors.New("publickeyerror")}pubInterface,err:=x509.ParsePKIXPublicKey(block.Bytes)iferr!=nil{returnnil,err}pub:=pubInterface.(*rsa.PublicKey)returnrsa.EncryptPKCS1v15(rand.Reader,pub,origData)}//解密funcRsaDecrypt(ciphertext[]byte)([]byte,error){block,_:=pem.Decode(privateKey)ifblock==nil{returnnil,errors.New("privatekeyerror!")}priv,err:=x509.ParsePKCS1PrivateKey(block.Bytes)iferr!=nil{returnnil,err}returnrsa.DecryptPKCS1v15(rand.Reader,priv,ciphertext)}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式