Skip to content

Instantly share code, notes, and snippets.

@muhasturk muhasturk/Crypto.py
Last active Nov 12, 2015

Embed
What would you like to do?
#!/usr/bin/env python3
import time
class Crypto():
def __init__(self):
self.start_time = time.clock()
def gcd_recursive(self, n, m):
return n if m == 0 else self.gcd_recursive(m, n % m)
def gcd_iterative(self, n, m):
while m:
n, m = m, n % m
return n
def extended_gcd_recursive(self, n, m):
if n == 0:
return (m, 0, 1)
else:
g, u, t = self.extended_gcd_recursive(m % n, n)
return (g, t - (m // n) * u, u)
def extended_gcd_iterative(self, n, m):
x,y = 0, 1
t, u = 1, 0
while m:
n, (q, m) = m, divmod(n,m)
x, t = t - q*x, x
y, u = u - q*y, y
return (n, t, u)
def modular_inverse(self, n, m):
g, t, u = self.extended_gcd_recursive(n, m)
if g != 1:
raise BaseException("\t{1} and {2} is not co-prime.\n"
"Therefore there is no modular inverse of {1}".format(n, m))
else:
return t % m
def chinese_remainder_theorem(self, items):
m = 1
for a, M in items:
m *= M
result = 0
for a, M in items:
y = m // M
g, t, u = self.extended_gcd_recursive(M, y)
if g != 1:
raise BaseException("{} and {} is not pairwise co-prime".format(M, y))
result += a * u * y
return result % m
def phi(self, n):
amount = 0
for k in range(1, n + 1):
if self.gcd_iterative(n, k) == 1:
amount += 1
return amount
def fast_modular_exponentiation(self, base, power, mode):
c = 0
d = 1
binary_power = "{0:b}".format(power)
int_power = int(binary_power)
len_number = len(str(abs(int_power)))
for i in range(len_number-1, -1, -1):
c *= 2
d = (d*d) % mode
if binary_power[i] == 1:
c += 1
d = (d*a) % mode
return d
def shift_cipher(self, text, key, mode = "e"):
result = ""
for i in text:
ascii_code = ord(i) - key if mode[0] == "d" else ord(i) + key
result += chr(ascii_code)
return result
def get_chars(self):
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
'abcdefghijklmnopqrstuvwxyz' + \
'0123456789' + \
':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\'
def generate_key():
shuffled = sorted(self.get_chars(), key=lambda k: random.random())
return dict(zip(chars, shuffled))
def subsitution_chipher_encrypt(key, plaintext):
return ''.join(key[l] for l in plaintext)
def subsitution_chipher_decrypt(key, ciphertext):
flipped = {v: k for k, v in key.items()}
return ''.join(flipped[l] for l in ciphertext)
def __del__(self):
print("\nFinished in: \t{}".format(time.clock() - self.start_time))
if __name__ == '__main__':
k = Crypto()
result = k.fast_modular_exponentiation(base=7, power=560, mode=561)
# items = [(9,13), (8,11), (1,7)]
# k.chinese_remainder_theorem(items)
print("Result:\t{}\n".format(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.