在Python Gae和Clien之间传递加密数据

2024-10-01 05:02:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图学习如何在服务器(pythongae)和客户端(jquery)之间传递加密数据

下面是服务器上代码片段的草图:

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)

publicKey        =  key.publickey()
clearText        =  "this is a test message"
b64Text          =  base64.b64encode(clearText)
ecryptedText     =  publicKey.encrypt(b64Text,32)

b64DecryptedText =  key.decrypt(encryptedText)  
clearText        =  base64.b64decode(b64DecryptedText)

我不明白什么作为公钥传递给客户机,客户机可以使用公钥进行加密 (使用http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js


Tags: key服务器客户端客户机jsrandomjquerygenerator
1条回答
网友
1楼 · 发布于 2024-10-01 05:02:39

1。向客户端发送公钥

客户机只需要公钥来加密服务器可以解密的内容。RSA公钥由模n和公共指数e组成。简单的方法是将这两部分作为十六进制编码字符串发送。你知道吗

modulus = hex(key.publickey().n)[2:-1]
exponent = hex(key.publickey().e)[2:-1]

2。使用公钥加密

CryptoJS不提供RSA实现,但是jsbnGitHub)提供。我们将公共组件发送为十六进制是件好事,因为jsbn希望模数和公共指数为十六进制编码字符串:

var rsa = new RSA();
rsa.setPublic(n_string, e_string);
var res = rsa.encrypt(plaintext);

请记住,RSA只能加密不比模大的数据。如果生成1024位密钥,则不能加密大于1024位的数据。如果你想加密更大的数据,你需要Hybrid Encryption例如AES。你知道吗

jsbn也只使用pycrypto支持的PKCS#1v1.5填充。您可以尝试使用尚未合并的pull request #3来获取PKCS#1v2oaep,它比v1.5更安全。你知道吗

三。python中的解密

jsbn返回一个十六进制编码的密文。您可以按照自己的意愿安全地发送它,但在python中解密之前需要将它解码(未显示)为字节。你知道吗

sentinel = Random.new().read(32) # denotes the error result of the decryption 
cipher = PKCS1_v1_5.new(key) # private key
message = cipher.decrypt(ciphertext, sentinel)
if sentinel != message:
    print("success: " + str(message))
else:
    print("failure")

相关问题 更多 >