python编写一个RSA加密工具类使用指定的公钥私钥进行数据加密
时间: 2024-05-12 07:20:20 浏览: 263
以下是一个Python编写的RSA加密工具类,可以使用指定的公钥和私钥进行数据加密和解密。
```python
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
class RSAUtil:
def __init__(self, public_key=None, private_key=None):
if public_key:
self.public_key = RSA.importKey(public_key)
if private_key:
self.private_key = RSA.importKey(private_key)
def generate_key(self, bits=2048):
self.key = RSA.generate(bits)
self.public_key = self.key.publickey()
self.private_key = self.key
def export_public_key(self):
return self.public_key.exportKey().decode('utf-8')
def export_private_key(self):
return self.private_key.exportKey().decode('utf-8')
def encrypt(self, data):
cipher = PKCS1_v1_5.new(self.public_key)
ciphertext = cipher.encrypt(data.encode('utf-8'))
return base64.b64encode(ciphertext).decode('utf-8')
def decrypt(self, ciphertext):
cipher = PKCS1_v1_5.new(self.private_key)
data = cipher.decrypt(base64.b64decode(ciphertext), None)
return data.decode('utf-8')
```
使用示例:
```python
public_key = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQ8QuKZ4kbwYpSfS+/x7c9j3q
m7C4Jz4hF7QZbWkR+Yw5OfNlJN7V9yWdFyKv5/5a5e/7p8W+5g5w6x+U6H7A9Xy
6XOgB+OznPzjL6LZMcgJZM6aKj+Q2QJXOyRrmtURjI3DKb3L+1s3qE0GwX9AxRj
OOJQ2F+I6rT8CnG3qQIDAQAB
-----END PUBLIC KEY-----"""
private_key = """-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANDxC4pniRvBilJ
9L7/Htz2PeqbsLgnPiEXtBltaRH5jDk585ySTe1fclnRcir+f/lrl7/unxb7mDn
DrH5TofsD1fLpc6AH47Oc/PMsotkxyAlkzpoqP5DZAlc7JGua1RGMyNwyW9y/tb
N6hNBsF/QMUYziUNhfiOq0/Apxt6kAgMBAAECgYB6xJU+HcOQkFTe6LfZwzJZP6
M+0X9R6jJvI2+1rI0rC8BZqJj1f+Gdp0zB72yU9X+U6uuJU6NcU6xZJ/l2bI6+P
D0i/jz/9y+XmVksjTupm2n0JrW+LzqY3s3sMz7Jqu0Wf9X7El3q+3uK7VklGmxRZ
Y37hJ1t2Qz0j4OEx9QJBAOcPzKjgV+JWJ5Z5wGZfz5a1+EpMsfW2Ji7KT/ak5zL
EFa+D5lGw5Y5K5zg/UfjFtW8uV7q3t+G5V7S5bRmBvECQQDQ1QOT4n4BhrE0oIb
Lr1Q2rT/GJ0/cZ6Y1qIzEBZiJc0oUkXyvPc6Ugwi6U1x6uvFQZwY+ZU84gDuxzHI
v7eZAkEA1iLcJx+0zLw5LV5H5lGZf1FZ5gOVf7F3tAVh9V7PzOyBjFCYiYtZP4V4
4jQO4+TmIliE9XrTnTJ2A/3qf3zN8wJBAI6zohsJvA9+hUW8yUzC6gMn6BzE6Q2
TwfzG6b0i6Gv6cWd9XgU6JF+6xkH0CQe6OXJFzg0b6P7+TTH0y9XrECQAsTJIfO
s+1aZLs0GpPfOJz7VhN9l9X7V/Ox5tDgYhZiJtZ8z4ZBEmj4N7JmH2m9yjg=
-----END PRIVATE KEY-----"""
rsa = RSAUtil(public_key, private_key)
# 加密
data = "hello world"
encrypted_data = rsa.encrypt(data)
print("加密后的数据:", encrypted_data)
# 解密
decrypted_data = rsa.decrypt(encrypted_data)
print("解密后的数据:", decrypted_data)
```
阅读全文