python基于RSA算法的非对称数字签名,要求,p,q不需要大素数,普通素数即可,但p,q,e要求为可输入数字,认证信息为任意可输入数字
时间: 2023-10-14 10:06:01 浏览: 69
非对称加密算法 数字签名算法
5星 · 资源好评率100%
以下是基于RSA算法的非对称数字签名的Python代码示例:
```python
import random
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def extended_gcd(a, b):
if a == 0:
return (b, 0, 1)
else:
gcd, x, y = extended_gcd(b % a, a)
return (gcd, y - (b // a) * x, x)
def mod_inv(a, m):
gcd, x, y = extended_gcd(a, m)
if gcd != 1:
raise Exception('Modular inverse does not exist')
else:
return x % m
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def generate_key(p, q, e):
if (not is_prime(p)) or (not is_prime(q)):
raise Exception('p or q is not prime')
n = p * q
phi = (p - 1) * (q - 1)
if gcd(phi, e) != 1:
raise Exception('e is not coprime to phi')
d = mod_inv(e, phi)
return ((n, e), (n, d))
def sign(message, private_key):
n, d = private_key
m = int(message)
return pow(m, d, n)
def verify(message, signature, public_key):
n, e = public_key
m = int(message)
s = pow(signature, e, n)
return s == m
# Example usage
p = 17
q = 19
e = 7
public_key, private_key = generate_key(p, q, e)
print('Public key:', public_key)
print('Private key:', private_key)
message = input('Enter message to sign: ')
signature = sign(message, private_key)
print('Signature:', signature)
valid = verify(message, signature, public_key)
if valid:
print('Signature is valid')
else:
print('Signature is not valid')
```
在代码中,`generate_key()`函数用于生成密钥对,`sign()`函数用于对消息进行签名,`verify()`函数用于验证签名。
需要注意的是,由于本算法不要求p,q为大素数,因此安全性较低,实际使用中应当使用大素数。同时,在签名时需要将待签名的消息转换为整数类型。
阅读全文