利用crytoapi,用python写一个可视化窗口,要求用户选择文件,将文件的数字签名显示出来
时间: 2023-07-15 22:13:10 浏览: 162
以下是一个使用 `cryptography` 模块和 `tkinter` 模块实现的可视化窗口,可以让用户选择文件,然后显示文件的数字签名:
```python
import tkinter as tk
from tkinter import filedialog
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key
class MainWindow(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("数字签名")
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_file_button = tk.Button(self, text="选择文件", command=self.select_file)
self.select_file_button.pack()
self.signature_label = tk.Label(self, text="")
self.signature_label.pack()
def select_file(self):
file_path = filedialog.askopenfilename()
if file_path:
signature = self.calculate_signature(file_path)
self.signature_label.config(text="文件数字签名:\n" + signature)
def calculate_signature(self, file_path):
with open(file_path, "rb") as f:
data = f.read()
private_key = load_pem_private_key(PRIVATE_KEY.encode(), password=None)
signature = private_key.sign(data, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
return signature.hex()
PRIVATE_KEY = """
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQC6fzH9LwOZ0s0Qj2JqDzL4F6Xi8QMa0qzA/+7uNoMwz2X9hzXb
k6U9C0g9WqXcavv9hLk/3TlK2fC7WwG8i5s5vhI8VXK1N7M+uFDRB6h71eQrJ3/k
DF6mKfHJ8FmjIDJgE6HNxL+ZI0J8tj+Rvi3jgC7lyeBliK+JvO6pD3T/ewIDAQAB
AoGAWovXhyfDf0s5a5K4KCOJy6n+3iN5eYlH5DkHjwKQjxOJwh1gNnlz0QntZ7OQ
Z9U7UzJdG3DqL2z4mzjMxAqV7eR9T5U/1zR7N2V2o7Z8v5zLm8iV93aFgFzKsaq4
3W4vDknzvUu5dFJwYhGZ5Q4J7zQv0uKQxEsZrQ5s9DpZ4KkCQQDdP4xQvX2Gz0dQ
A4sNk2WQd6S3z0PsnOvq0JgQ3t0nRQx9dUW6qgK1oqfzjJwQf/2gxH5mQ4Bt+8I8
6V2k9N7tAkEA0G+zZ6h4oYnE9Za+6j1QY3c/y5Bjx3t8zVKBXjiv5yYV7YmAC8Yy
/6nMztt5pRw8J6+J+KdJVWyYdA5Oy3eOSQJBAKQ9lBkYVONNj8qk+ZtRlxGUCJrW
U/l/Lg4Dn3fL0Mv2Ls++dZ5gUwsyvE4hZs3FJ4R6u2T5mNQd3rGzP1RfC4ECQQCO
yv4qZJ4P7ZK5+K9XwSvE4hMeNzYcA1iSh2Z+2H4bV2L/7Zj7tX9kWqqBxVk6tB4A
B/kl5F5BjJbku5fDCrKhAkEA2pZf4X+L/zDk2+G6pvK1ZuLLEnYcP9HxRy4uYI61
E5aE9y1M2ZGm9DfBvyyhG2bN4sM3VQm+RQs8aYp6/NZrXw==
-----END RSA PRIVATE KEY-----
"""
if __name__ == '__main__':
root = tk.Tk()
app = MainWindow(master=root)
app.mainloop()
```
这个程序使用的是一个硬编码的私钥,你需要替换为你自己的私钥。在此程序中,当用户选择一个文件之后,程序会计算文件的数字签名并将其显示在窗口中。
阅读全文