我是密码学的新手。我想从服务器端生成 RSA 密钥对并将其发送到所有客户端(浏览器)。但在此之前,我通过简单地在 python 中加密数据并通过 pubnub 发送到 index.html 文件并尝试在 JavaScript 中对其进行解密来测试场景。问题是当我通过以下方式进行加密时;
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
enc = enc_data[0]
并发送加密数据enc,它给了我这个错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 2: invalid continuation byte
我试图将其转换为
enc = base64.b64encode(enc_data[0])
并且发送没有错误。但是 JS 解密方法得到 None
var enc_from_python = $('#input').val();
console.log("ENCRYPTED data:", enc_from_python);
var decrypt = new JSEncrypt();
decrypt.setPrivateKey($('#privkey').val());
var uncrypted = decrypt.decrypt(enc_from_python);
console.log(">>>",uncrypted); //<-- this is None ! why ?
这两个代码都可以自己很好地进行编码/解码。我还尝试使用从 python 接收的密钥对对 JS 中的数据进行编码/解码,效果很好。我猜问题出在 Pycrypto 编码数据的 unicode 编码格式不匹配。谁能告诉我我在这里错过了什么。
Python的完整代码:
import time
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from Crypto.PublicKey import RSA
from Crypto import Random
import base64
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'
pnconfig.publish_key = 'demo'
channel = "my_channel"
pubnub = PubNub(pnconfig)
def my_publish_callback(envelope, status):
if not status.is_error():
pass # Message successfully published to specified channel.
else:
pass # Handle message publish error. Check 'category' property to find out possible issue
time.sleep(1)
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
#enc = enc_data[0]
enc = base64.b64encode(enc_data[0])
print enc
#print type(enc_data[0])
print '----ENCRYPTED DATA----'
print ''
print '----DECRYPTED DATA begin----'
print key.decrypt(enc_data[0])
print '----DECRYPTED DATA end----'
pubnub.publish().channel(channel).message({"data": enc , "private": (key.exportKey()), "public" : (public_key.exportKey())}).async(my_publish_callback)
完整的JS代码是;
<!doctype html>
<html>
<head>
<title>JavaScript RSA Encryption</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.min.js"></script>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.12.0.min.js"></script>
<script type="text/javascript">
// Call this code when the page is done loading.
$(function() {
pubnub = new PubNub({
publish_key: 'demo',
subscribe_key: 'demo'
});
pubnub.subscribe({
channels: ['my_channel']
});
pubnub.addListener({
message: function(message) {
var msg = message.message;
console.log("msg:" + JSON.stringify(msg));
if (msg.private){
$("#privkey").val(msg.private);
}
if(msg.public){
$("#pubkey").val(msg.public);
}
if(msg.data){
$("#input").val(msg.data);
}
}
})
// Run a quick encryption/decryption when they click.
$('#testme').click(function() {
var enc_from_python = $('#input').val();
console.log("ENCRYPTED data:", enc_from_python);
// Decrypt with the private key...
var decrypt = new JSEncrypt();
decrypt.setPrivateKey($('#privkey').val());
var uncrypted = decrypt.decrypt(enc_from_python);
console.log(">>>",uncrypted); //<-- this is None ! why ?
// Now a simple check to see if the round-trip worked.
if (uncrypted == $('#input').val()) {
alert('It works!!!');
}
else {
alert('Something went wrong....');
}
});
});
</script>
</head>
<body>
<label for="privkey">Private Key</label><br/>
<textarea id="privkey" rows="15" cols="65"> </textarea><br/>
<label for="pubkey">Public Key</label><br/>
<textarea id="pubkey" rows="15" cols="65"> </textarea><br/>
<label for="input">Text to decrypt:</label><br/>
<textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
<input id="testme" type="button" value="Decrypt Me!!!" /><br/>
</body>
</html>