[new] 1、用Python或Sage实现RSA算法的加密、解密、签名/验证签名
使用sage实现RSA算法进行加密、解密、签名/验证签名
#GenerateKeys - e, d, N
def generateKeys(bits):
p = random_prime(2**(bits//2), lbound = 2**(bits//2-1))
q = random_prime(2**(bits//2), lbound = 2**(bits//2-1))
N = p * q
EulerN = (q-1) * (p-1)
e = randint(1, EulerN)
while(gcd(e, EulerN)! = 1):
e = randint(1, EulerN)
d = inverse_mod(e, EulerN)
return e, d, N
#Encode func
def encode(M):
m = str(M)
return sum(ord(m[i]) * pow(256, i) for i in range(len(m)))
#Decode func
def decode(n):
m = ""
while(n > 0):
m += chr(n%256)
n = n//256
return m
#Encrypt func
def encrypt(m, e, N):
return lift(mod(m, N)**e)
#Decrypt func
def decrypt(n,d,N):
return lift(mod(n, N)**d)
#RSA e.g.
e, d, N = generateKeys(1024)
M_encode = encode('Iamttyy')
N_encrypt = encrypt(M_encode, e, N)
N_decrypt = decrypt(N_encrypt, d, N)
M_decode = decode(N_decrypt)
print M_encode
print M_decode
#Signature e.g.
Signature = encrypt(M_encode, d, N)
Verify_me = decrypt(signature, e, N)
print 'Signature:'
print signature
print 'Verify_me:'
print Verify_Me
print 'is same as'
print M_encode
print 'Accept -- else: Reject'
[new]2、用Python或Sage实现DH秘钥交换协议的。
更新版本
#Set Up and Down boundary
Up = 2^32
Down = 2^16
#Random prime - q
q = random_prime(Up, lbound=Down)
#Root - g
while True:
g = randint(1, q-1)
#Add judgement of g^(q-1) mod q ==1
if(multiplicative_order(mod(g, q)) == q-1):
break
#Random Private Key1
X1 = randint(1, q-1)
#Calu
Y1 = mod(g, q)^X1
#Random Private Key2
X2 = randint(1, q-1)
#Calu
Y2 = mod(g, q)^X2
#Calu
Key1 = mod(Y2, q)^X1
Key2 = mod(Y1, q)^X2
#Verify
if Key1 == Key2:
print 'Accept!'
else :
print 'Reject!'
1、用Python或Sage实现RSA算法的加密、解密、签名/验证签名
python实现
注: 不要将文件名写成rsa.py
#-*-coding : utf-8 -*-
#anthor: tyty
import rsa
(PubK, PriK) = rsa.newkeys(1024)
print PubK
print PriK
#SaveToFile .pem
# with open('Public_Key.pem', 'w+') as f:
# f.write(PubK.save_pkcs1().decode())
# with open('Privacy_Key.pem', 'w+') as f:
# f.write(PriK.save_pkcs1().decode())
#Message
M = "tyty is a boy"
#Encryption
encry_M = rsa.encrypt(M.encode(), PubK)
print "encrypt M = " + encry_M
#Decryption
decry_M = rsa.decrypt(encry_M, PriK).decode()
print "decrypt M = " + decry_M
#Signature
M = "tyty"
signature = rsa.sign(M.encode(), PriK, 'SHA-1')
print signature
#Verify
rsa.verify(M.encode(), sign, PubK) # right
rsa.verify("tttt", signature, PubK) # wrong
2、用Python或Sage实现DH秘钥交换协议的。
Sage实现
注:开头须判断p是否为素数
#isPrime
sage: a = 787
sage: factor(a)
787
#param
sage: p = 787
sage: F = GF(p)
#root
sage: g = F(2)
#random int x
sage: x = randint(1, 786);x
621
sage: X = g^x;X
673
#random int y
sage: y = randint(1, 786);y
213
sage: Y = g^y;Y
627
#shared secret key
sage: Y^x
211
sage: X^y
211
网友评论