1
回答
python rsa 加密解密
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

win7+python3.6

pip install rsa

用rsa自动生成的密码对,

公钥加密,私钥解密=ok

私钥加密=ok,但是不能公钥解密

 

代码如下:

import rsa

# 导入密钥
with open('public.pem','r') as f:
    pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())

with open('private.pem','r') as f:
    privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())

print(pubkey)
print(privkey)

# rsa加密
def rsaEncrypt(str):
    # 明文编码格式
    content = str.encode('utf-8')
    # 公钥加密
    crypto = rsa.encrypt(content, pubkey)
    return (crypto, privkey)


# rsa解密
def rsaDecrypt(str, pk):
    # 私钥解密
    content = rsa.decrypt(str, pk)
    con = content.decode('utf-8')
    return con

plain_text="hello,世界,你好"*5
print(plain_text)
#公钥加密,私钥解密
print("公钥加密,私钥解密")
(a, b) = rsaEncrypt(plain_text)
print('加密后密文:')
print(a)
content = rsaDecrypt(a, b)
print('解密后明文:')
print(content)

print()
print("私钥加密,公钥解密")
crypto = rsa.encrypt(plain_text.encode("utf-8"), privkey)
print("私钥加密成功")
decrypto = rsa.decrypt(crypto, pubkey)
print("公钥解密成功")

运行结果:

...

hello,世界,你好hello,世界,你好hello,世界,你好hello,世界,你好hello,世界,你好
公钥加密,私钥解密
加密后密文:
b'\x1as8\x88\xc5\x84r\xb5\x94\xcdt1o4\x0b:~\xafls\xdb\x964uL\xf5\x93\x02&pA\x8f\xf2b\xff o\xe0\xce\xa95\tN\x0e\xd1\x08\x1f-c\xb0\\[1\xc4=\xc0\xc4\xd5\xf8\xabt\xbaG\xff\xca\x16\x1a5;Ec:\x9d,\xaccb\xbe\xc7\xaee\x05\x88\xd6]\xa5\xf2\xc3\x95VBF\xa3\xa6\xa0e\xeeo\x91\x90j\xba\xa0\x13\xe5f\xf6\x9a\xfa\x9f\xd4\x02\xf9y\xbdI\xb5dy\xbc\xe7`\xdb\xa1S)\xa9\xea\xb0\x8e\t\xb9SQ\xe6Bq\x1e\xadM~\xfb\xfd\x9a\xf8\xc65\xca\xae\x87\x04Y\x07S\xba$\xb6\xe8\x90D\xee\xec>n\xd4\n\xe3d8\x11e\xa4\xa2<\x07\x89\xa9\\\x1d\x0b\xbc\xe1R\x81\xd1\xabAL\x15\xdd\xb0\xe0\xc9k\x90\xb3?o\x9b\x1b\xf354\xa9\xc0\xcd8"\xfa\x12\xbdeM\xc9\xd9\xac\x82\x96x\xd7\x10`\xbf\xbb\xad\xf4\xf8\x8b\\)\xd0*I\x89\x02\\\xae\xd5{@\xf3*\x1b%\xc9/\xaa\xdb8\x98\xeb\x82\xbb{\x99\x12'
Traceback (most recent call last):
  File "C:/Users/Peter/PycharmProjects/TestPython/rsa/SimpleRsa.py", line 44, in <module>
解密后明文:
    decrypto = rsa.decrypt(crypto, pubkey)
hello,世界,你好hello,世界,你好hello,世界,你好hello,世界,你好hello,世界,你好

  File "C:\Users\Peter\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rsa\pkcs1.py", line 232, in decrypt
私钥加密,公钥解密
    decrypted = priv_key.blinded_decrypt(encrypted)
私钥加密成功
AttributeError: 'PublicKey' object has no attribute 'blinded_decrypt'

Process finished with exit code 1
 

就是最后的一句,公钥解密失败了

<无标签>
举报
public_me
发帖于9个月前 1回/576阅
顶部