参考http://www.liaoxuefeng.com/article/00137389255913089a316bc2ccb48d3b2323759fecd4cf8000

维基百科给出的RSA算法简介如下:

假设Alice想要通过一个不可靠的媒体接收Bob的一条私人讯息。她可以用以下的方式来产生一个公钥和一个私钥:

    随意选择两个大的质数p和q,p不等于q,计算N=pq。
    根据欧拉函数,不大于N且与N互质的整数个数为(p-1)(q-1)
    选择一个整数e与(p-1)(q-1)互质,并且e小于(p-1)(q-1)
    用以下这个公式计算d:d × e ≡ 1 (mod (p-1)(q-1))
    将p和q的记录销毁。

(N,e)是公钥,(N,d)是私钥。(N,d)是秘密的。Alice将她的公钥(N,e)传给Bob,而将她的私钥(N,d)藏起来。


#!/usr/bin/env python

def range_prime(start, end):
    l = list()
    for i in range(start, end+1):
        flag = True
        for j in range(2, i):
            if i % j == 0:
                flag = False
                break
        if flag:
            l.append(i)
    return l

def generate_keys(p, q):
    #numbers = (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)
    numbers =range_prime(10, 100)
    N = p * q
    C = (p-1) * (q-1)
    e = 0
    for n in numbers:
        if n < C and C % n > 0:
            e = n
            break
    if e==0:
        raise StandardError("e not found")

    d = 0
    for n in range(2, C):
        if(e * n) % C == 1:
            d = n
            break
    if d==0:
        raise StandardError("d not found")
    return ((N, e), (N, d))

def encrypt(m, key):
    C, x = key
    return (m ** x) % C


decrypt = encrypt

if __name__ == '__main__':
    pub, pri = generate_keys(47, 79)
    L = range(20, 30)
    C = map(lambda x: encrypt(x, pub), L)
    D = map(lambda x: decrypt(x, pri), C)
    print "keys:", pub, pri
    print "message:", L
    print "encrypt:", C
    print "decrypt:", D

keys: (3713, 11) (3713, 1631)
message: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
encrypt: [406, 3622, 3168, 134, 3532, 263, 1313, 2743, 2603, 1025]
decrypt: [20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L]



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐