Python编程实现ECC,随机数取6
时间: 2023-11-19 22:28:24 浏览: 141
好的,以下是Python编程实现ECC,随机数取6的示例代码:
```python
from Crypto.Util.number import long_to_bytes
from hashlib import sha256
import math
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = -3
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
d = 6
def point_addition(P, Q):
if P is None:
return Q
if Q is None:
return P
if P == Q:
if P[1] == 0:
return None
slope = (3 * P[0]**2) * pow(2 * P[1], -1, p)
else:
if P[0] == Q[0]:
return None
slope = (Q[1] - P[1]) * pow(Q[0] - P[0], -1, p)
x = (slope ** 2 - P[0] - Q[0]) % p
y = (slope * (P[0] - x) - P[1]) % p
return (x, y)
def scalar_multiplication(d, P):
Q = None
for i in range(math.ceil(math.log2(n))):
if ((d >> i) & 1) == 1:
Q = point_addition(Q, P)
P = point_addition(P, P)
return Q
def get_public_key(d, Gx, Gy, a, b, p):
Q = scalar_multiplication(d, (Gx, Gy))
return Q
def sign_message(message, d, Gx, Gy, a, b, p):
z = int.from_bytes(sha256(message).digest(), byteorder='big')
k = 2
while True:
x, y = scalar_multiplication(k, (Gx, Gy))
r = x % n
if r == 0:
k += 1
continue
s = (pow(k, -1, n) * (z + r * d)) % n
if s == 0:
k += 1
continue
break
return (r, s)
def verify_signature(message, signature, Q, Gx, Gy, a, b, p):
r, s = signature
if r < 1 or r > n-1 or s < 1 or s > n-1:
return False
z = int.from_bytes(sha256(message).digest(), byteorder='big')
w = pow(s, -1, n)
u1 = (z * w) % n
u2 = (r * w) % n
x, y = point_addition(scalar_multiplication(u1, (Gx, Gy)), scalar_multiplication(u2, Q))
if x is None or y is None:
return False
if r == x % n:
return True
else:
return False
# 生成公钥
Q = get_public_key(d, Gx, Gy, a, b, p)
print("公钥: ({0}, {1})".format(hex(Q[0]), hex(Q[1])))
# 对消息进行签名
message = b"Hello, World!"
signature = sign_message(message, d, Gx, Gy, a, b, p)
print("签名: ({0}, {1})".format(hex(signature[0]), hex(signature[1])))
# 验证签名的有效性
valid = verify_signature(message, signature, Q, Gx, Gy, a, b, p)
print("签名是否有效: ", valid)
```
在这段代码中,我们使用了secp256k1曲线的参数。我们首先使用随机数6生成私钥,并使用私钥生成对应的公钥。然后,我们使用私钥对消息进行签名,并使用公钥来验证签名的有效性。
请注意,这里的签名算法使用了ECDSA算法,这是一种基于ECC的数字签名算法。
阅读全文