Last active
December 16, 2015 11:28
-
-
Save TheEmpty/5427037 to your computer and use it in GitHub Desktop.
Python PGP (attempt)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pgp | |
| print("Generating keys...") | |
| p = pgp.generateLargePrime(1024) | |
| q = pgp.generateLargePrime(1024) | |
| mod = p * q | |
| print("Generating public key...") | |
| public = pgp.generatePublic(p, q) | |
| print("Generating private key...") | |
| private = pgp.generatePrivate(p, q, public) | |
| p, q = None, None # remove p and q values | |
| print("pub =", public) | |
| print("priv =", priv) | |
| print("mod =", mod) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random, fractions | |
| def generatePublic(p, q): | |
| random.seed() | |
| num = random.randint((p - 1)*(q - 1), (p - 1)*(q - 1) + 1000) | |
| if num % 2 is 0: | |
| num += 1 | |
| while True: | |
| if num < p * q: | |
| if fractions.gcd(num, (p-1)*(q-1)) is 1: | |
| return num | |
| num += 2 | |
| def generatePrivate(p, q, e): | |
| random.seed() | |
| while True: | |
| num = random.getrandbits(1024) | |
| res = (num * e) % ((p - 1) * (q - 1)) | |
| if res is 1: | |
| return num | |
| def crypt(mod, key, data, hashes = 50): | |
| encrypted = [] | |
| for v in data: | |
| for i in range(0, hashes + 1): | |
| v = (v ** key) % mod | |
| encrypted.append(v) | |
| return list(map(int, encrypted)) | |
| def miller_rabin_pass(a, s, d, n): | |
| a_to_power = pow(a, d, n) | |
| if a_to_power == 1: | |
| return True | |
| for i in range(0, s-1): | |
| if a_to_power == n - 1: | |
| return True | |
| a_to_power = (a_to_power * a_to_power) % n | |
| return a_to_power == n - 1 | |
| def miller_rabin(n): | |
| d = n - 1 | |
| s = 0 | |
| while d % 2 == 0: | |
| d >>= 1 | |
| s += 1 | |
| for repeat in range(0, 20): | |
| a = 0 | |
| while a == 0: | |
| a = random.randrange(n) | |
| if not miller_rabin_pass(a, s, d, n): | |
| return False | |
| return True | |
| def generateLargePrime(bits = 1024): | |
| random.seed() | |
| # Odd bit number | |
| number = random.getrandbits(bits) | |
| if number % 2 is 0: | |
| number += 1 | |
| # Check for prime | |
| while True: | |
| if miller_rabin(number): | |
| return number | |
| number += 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment