RSA is an asymmetric encryption algorithm. It is a widely used public key encryption algorithm. It is mainly used to encrypt information and digital signatures. This article describes how to implement the rsa algorithm code in python. If you are interested, join us in learning. The RSA algorithm is an asymmetric encryption algorithm and is a widely used public key encryption algorithm, the main applications are encrypted information and digital signatures.
The RSA algorithm provided by Wikipedia is described as follows:
Assume that Alice wants to receive Bob's private message through an unreliable media. She can generate a public key and a private key in the following ways:
Select two large prime numbers p and q at will. p is not equal to q and N = pq is calculated.
According to the Euler's function, the number of integers that are not greater than N and intersect with N is (1) (q-1)
Select an integer e and (1) (q-1), and e is less than (1) (q-1)
Use the formula below to calculate d: d × e limit 1 (mod (p-1) (q-1 ))
Destroy records of p and q.
(N, e) is the public key, (N, d) is the private key. (N, d) is a secret. Alice transmits her public key (N, e) to Bob and hides her private key (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]
The above section describes how to use python to implement the rsa algorithm code. I hope it will help you!