简单实现rsa加密算法
rsa的基本步骤如下:
# 1. 产生两个比较大的素数p,q
# 2. 计算 N = pq 和phi = (p-1) * (q - 1)
# 3. 找到一个整数e满足条件 (1 < e < phi)并且与phi是互质的: gcd(e, phi) = 1
# 4. 计算私钥 d, 满足条件1 < d <phi, 并且是e的模逆ed = 1 (mod phi)
# 5. 公共密钥就是(N, e),私钥就是(N, d)
# naive rsa implementation # p = 11 , q = 3 # import math import random p = 11 q = 3 N = p * q e = 3 # prime to ( p - 1)* (q - 1) # public key: ( N, e ) = (33, 3) # private key: d = 7 d = 7 # encrypt #--------------- # message m = 32 result = 1 exp = e base = m while (exp > 0): if ( exp & 1): result = result * base % N exp = exp >> 1 base = (base * base) % N c = result print 'ciphertext:' print c # decrypt #------------------ result = 1 exp = d base = c while (exp > 0): if ( exp & 1): result = result * base % N exp = exp >> 1 base = (base * base) % N dm = result print 'decypher text:' print dm
转载请注明出处