需求
一个json数据序列化成字符串,使用python rsa的公钥进行加密,go使用rsa私钥对密文解密 还原原始json
注
尝试使用AES算法,但发现python加密的aes数据,go解开后不是明文,咱不知道原因,先换成rsa
python 具体实现
python实现rsa密钥的生成,对json数据进行加密
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
# ------------------------生成密钥对------------------------
def create_rsa_pair(is_save=False):
'''
创建rsa公钥私钥对
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私钥
public_key = f.publickey().exportKey() # 生成公钥
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
# 字符串指定编码(转为bytes)
text = text.encode('utf-8')
# 构建公钥对象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64编码,并转为字符串
text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
return text_encrypted_base64
# ------------------------解密------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
# 字符串指定编码(转为bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解码
text_encrypted = base64.b64decode(text_encrypted_base64)
# 构建私钥对象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
# 解码为字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
# 生成密钥对
# create_rsa_pair(is_save=True)
# public_key = read_public_key()
# private_key = read_private_key()
public_key, private_key = create_rsa_pair(is_save=True)
import json ,time
public_key = read_public_key()
a = {}
a['code'] = 300
a['msg'] = 'nma'
a['wxid'] = 'wasdfsdf'
a['t'] = int(time.mktime(time.localtime(time.time())))
print(a)
text = json.dumps(a)
text_encrypted_base64 = encryption(text, public_key)
print('密文:', text_encrypted_base64)
go实现对rsa进行解密
将python生成的密文串 写入到代码中进行测试
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/json"
"os"
"time"
"fmt"
)
type Result struct {
Code int `json:"code"`
Message string `json:"msg"`
Wxid string `json:"wxid"`
Time int64 `json:"t"`
}
//生成RSA私钥和公钥,保存到文件中
func GenerateRSAKey(bits int){
//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
//Reader是一个全局、共享的密码用强随机数生成器
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err!=nil{
panic(err)
}
//保存私钥
//通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
//使用pem格式对x509输出的内容进行编码
//创建文件保存私钥
privateFile, err := os.Create("private.pem")
if err!=nil{
panic(err)
}
defer privateFile.Close()
//构建一个pem.Block结构体对象
privateBlock:= pem.Block{Type: "RSA Private Key",Bytes:X509PrivateKey}
//将数据保存到文件
pem.Encode(privateFile,&privateBlock)
//保存公钥
//获取公钥的数据
publicKey:=privateKey.PublicKey
//X509对公钥编码
X509PublicKey,err:=x509.MarshalPKIXPublicKey(&publicKey)
if err!=nil{
panic(err)
}
//pem格式编码
//创建用于保存公钥的文件
publicFile, err := os.Create("public.pem")
if err!=nil{
panic(err)
}
defer publicFile.Close()
//创建一个pem.Block结构体对象
publicBlock:= pem.Block{Type: "RSA Public Key",Bytes:X509PublicKey}
//保存到文件
pem.Encode(publicFile,&publicBlock)
}
func RSA_Encrypt(password string,path string) string {
//打开文件
file,err:=os.Open(path)
if err!=nil{
panic(err)
}
defer file.Close()
//读取文件的内容
info, _ := file.Stat()
buf:=make([]byte,info.Size())
file.Read(buf)
//pem解码
block, _ := pem.Decode(buf)
//x509解码
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
//类型断言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//对明文进行加密
plainText := []byte(password)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
if err != nil {
panic(err)
}
//返回密文
cipherBase := base64.StdEncoding.EncodeToString(cipherText)
return cipherBase
}
func RSA_Decrypt(password string,path string) string {
//打开文件
file,err:=os.Open(path)
if err!=nil{
panic(err)
}
defer file.Close()
//获取文件内容
info, _ := file.Stat()
buf:=make([]byte,info.Size())
file.Read(buf)
//pem解码
block, _ := pem.Decode(buf)
//X509解码
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
crytedByte, _ := base64.StdEncoding.DecodeString(password)
//对密文进行解密
prPlainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, crytedByte)
//返回明文
return string(prPlainText)
}
func main(){
//生成密钥对,保存到文件
// GenerateRSAKey(2048)
//message:= "hello world"
//加密
cipherText:= "hFApKdStWeq8WNCLWf4N5aDBzmqS7zUC/IWmP7P8oEQb7vi8A40+XNnkIDsKkez8RIgI1HH4BFzXyHVyvgCCfCPTktWhWNZstKhAcTNsmSem4v5MTYCnHtYLM/xYpag2RjN/rJHDvyze1amXu6P3NHJlMANfF9NKdzhFtLTHDY0W+x12gG2h47pU1LW6R9XiW7QKG+D+8i6AjgkrwvEOIsDlXdfYbakrucm4htyo/9v0NaQcahs+8KgNamgYVdQNKvsg16pHu/6nrZeC+DBfI/4rlSIsGzvgQOiqQkR4WtzjLvktt96QbJ8LjG3bt2W0ZtM6bcpp1053RtNQRDc/vw==" // RSA_Encrypt(message,"public.pem")
//fmt.Println("加密后为:",string(cipherText))
//解密
plainText := RSA_Decrypt(cipherText, "private.pem")
var res2 Result
fmt.Println("解密后为:",plainText)
plainByte := []byte(plainText)
errs := json.Unmarshal(plainByte, &res2)
if errs != nil {
fmt.Println("json unmarshal error:", errs)
}
fmt.Println("res2 code:", res2.Code)
fmt.Println("res2 msg:", res2.Message)
fmt.Println("res2 msg:", res2.Wxid)
fmt.Println(time.Now().Unix() - res2.Time)
fmt.Println(res2)
fmt.Println(time.Now().Unix())
//fmt.Println("解密后为:",string(plainText))
}
这个样例基本上实现了一个demo,具体代码可以自行修改和适配