Document the project structure and setup while excluding local dependencies and IDE settings. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
# pip install rsa
|
|
import rsa
|
|
import base64
|
|
|
|
"""
|
|
非对称加解密需要一对密钥(公钥,私钥)
|
|
|
|
加密过程中,一般情况使用公钥加密,私钥解密
|
|
也能用私钥加密,公钥解密
|
|
"""
|
|
|
|
def create_key():
|
|
public_key, private_key = rsa.newkeys(1024) # 字节长度
|
|
# print("公钥", public_key)
|
|
# print("私钥", private_key)
|
|
return public_key, private_key
|
|
|
|
# 使用公钥加密,私钥解密
|
|
def encrypt_data(text, public_key):
|
|
bytes_text = text.encode("utf-8")
|
|
encrypted_text = rsa.encrypt(bytes_text, public_key)
|
|
return base64.b64encode(encrypted_text)
|
|
|
|
def decrypt_data(encrypted_text, private_key):
|
|
bytes_text = base64.b64decode(encrypted_text)
|
|
bytes_decrypted_text = rsa.decrypt(bytes_text, private_key)
|
|
return bytes_decrypted_text.decode("utf-8")
|
|
|
|
|
|
|
|
def main():
|
|
public_key, private_key = create_key()
|
|
|
|
source_data = "你好,世界!"
|
|
encrypted_text = encrypt_data(source_data, public_key)
|
|
print("base64的密文结果", encrypted_text)
|
|
decrypted_text = decrypt_data(encrypted_text, private_key)
|
|
print("解密结果", decrypted_text)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |