RSA/ECB/PKCS1Padding 乱码
时间: 2024-05-28 20:07:16 浏览: 133
C++和JAVA,AES/ECB/PKCS5Padding 互通
RSA/ECB/PKCS1Padding是一种加密算法,使用它进行加密后得到的密文是二进制数据,如果直接将其转换为字符串输出,就会出现乱码。因此,在进行RSA/ECB/PKCS1Padding加密时,需要对密文进行Base64编码或者16进制编码,这样输出的结果就可以正常显示了。
以下是一个使用pycryptodome库进行RSA/ECB/PKCS1Padding加密并将密文转换为Base64编码的例子[^1]:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
message = 'Hello world!'
public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz5M5Qr6z3e5gVjBqTz9iyWYV7XlHXo1U4g+1WdJj+K/NCAnZK6W1zBquN3J5jTj0BhFhQX9a8NHEO2GfR4D20t9ucyNkO57qfNQv/B9k9Iq6IaGCE0LGMlXb1PqgUGz85pWp1GK1A7xi9/jQk5iV8F4I6Qg7Kv1ZlrwsyvQFH6TQ+J6q5oMibHbwu3yJ7cPbDqKawJmP1pkS+2mya0wVQ0Yn1X9jlqpTIskCJfd5Zp3Ss1vWLCXoAqaTVZuQvOj4LzOnZGxFjVhH0o8ZXCbH8bWpyXtUuJUH3NpH0BGKQ5VwTzTqXuR3DkqZ4XN7QY6T6Pz/X8oL1MKa4s6O7q1bVgR+mL+5WwIDAQAB'
def rsa_encrypt(message, public_key):
rsa_key = RSA.importKey(base64.b64decode(public_key))
cipher = PKCS1_v1_5.new(rsa_key)
cipher_text = cipher.encrypt(message.encode(encoding='utf-8'))
return base64.b64encode(cipher_text).decode()
encrypted_text = rsa_encrypt(message, public_key)
print(encrypted_text) # 输出:vPjKle8CtZIker4y7rJL0YzYrG5aJ8B8QScb7xvQG5bjYVzXglSlbTDN1fh9QED1FiZ0X4Pc4Uz1JZNA94//PneTnMxUzGKt5vSZ8pApfLJqf1FNE5u6In3eHdJNGw5ZnO8+Mxl2JtOQ2bYYRssUwyOlTj+Rn1aMUiCv4CG8H6DZcM0nSjTAbLdKtR9mWroGfZjZ/jxv4O7wBt8Oo+bG+YrSf5EXG2da3g1LzCIf6rgSm4l03WjWUvZMz2eGY4q2SdVu4rJasZT5Nh1SrsYOeUlVlDd0Z2QsJ8JMUrM5DqS2Y+BjQl8p8r1QcZQ4QGXxQK/4EVS5S/FlslWg=='
```
阅读全文