Last active
May 5, 2025 15:59
-
-
Save Kaki-In/46d4365b0c4aa5734b44debc15c96d2e to your computer and use it in GitHub Desktop.
Crypt
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
from math import * | |
def divide(a,b): | |
return a//b,a%b | |
def get_bezout(a,b): | |
rnm2=a | |
rnm1=b | |
unm2=1 | |
unm1=0 | |
vnm2=0 | |
vnm1=1 | |
i=0 | |
while True: | |
i+=1 | |
nq,nr=divide(rnm2,rnm1) | |
if nr==0: | |
return rnm1,unm1,vnm1,i | |
rnm2,rnm1=rnm1,nr | |
unm2,unm1=unm1,unm2-nq*unm1 | |
vnm2,vnm1=vnm1,vnm2-nq*vnm1 | |
def get_inverse(a,n): | |
r,u,v,i=get_bezout(n,a) | |
return u%n | |
def mod_power(a,b,n): | |
bin_data=[int(i) for i in bin(b)[2:]] | |
bin_data.reverse() | |
exp=a | |
v=1 | |
for i in range(len(bin_data)): | |
if bin_data[i]: | |
v*=exp | |
v%=n | |
exp**=2 | |
exp%=2 | |
return v | |
def factors(n): | |
sqrtv=int(sqrt(n)) | |
factors=[] | |
for i in range(1,sqrtv+1): | |
if n%i==0: | |
factors.append(i) | |
r=[n//i for i in factors if not n==i**2] | |
r.reverse() | |
return factors+r | |
def prem_factors(n): | |
facts=factors(n) | |
p_facts=[] | |
for f in facts: | |
if len(factors(f))==2: | |
i=0 | |
df=f | |
while n%df==0: | |
i+=1 | |
df*=f | |
p_facts.append((f,i)) | |
return p_facts | |
class Key(): | |
def __init__(self,value,mod): | |
self.value=value | |
self.mod=mod | |
def is_valid(self): | |
return len(factors(self.mod))==4 | |
def get_phi(self): | |
pf1,pf2=prem_factors(self.mod) | |
return (pf1[0]-1)*(pf2[0]-1) | |
def encode(self,data): | |
return mod_power(data,self.value,self.mod) | |
def get_opposite_key(self): | |
return Key(get_inverse(self.value,self.get_phi()),self.mod) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment