๐ Secure/๐ Crypto
[Crypto] Python | RSA ์ํธ ์๊ณ ๋ฆฌ์ฆ ์ ์ฉ ์ฝ๋ + ์์
sa1t
2023. 9. 12. 10:23
๋ฐ์ํ
from random import randint
# ์๋ก ๋ค๋ฅธ 2๊ฐ์ ์์ ๊ณ ๋ฅด๊ธฐ
def is_prime(n):
if n<2:
return False
for i in range(2, int(n ** 0.5)+1):
if n%i==0:
return False
return True
def find_primes(start, end):
prime1 = prime2 = 0
while not is_prime(prime1):
prime1= randint(start, end -1)
while not is_prime(prime2):
prime2 = randint(start, end -1)
return prime1, prime2
# phi๋ฅผ ๊ตฌํ๊ณ , ์๋ก์์ธ e ๊ตฌํ๊ธฐ
# ์ ํด๋ฆฌ๋ ํธ์ ๋ฒ ์ด์ฉ
def gcd(a,b):
while b:
a,b = b, a%b
return a
def find_e(phi):
e = None
for i in range(2,phi):
if gcd(phi,i)==1: #phi=i, i=phi%i
e=i
break
return e
# ๊ฐ์ธํค d ์ฐพ๊ธฐ
def find_d(phi,e):
d=None
for i in range(phi//e,phi):
if e*i%phi==1:
d=i
break
return d
# ๊ณต๊ฐํค
def generate_keys():
n, e, d = 0, None, None
while e is None or d is None:
prime1, prime2 = find_primes(1000,10000)
n = prime1 *prime2 # ๊ณต๊ฐํค n
phi = (prime1 - 1)*(prime2 - 1)
e=find_e(phi) # ๊ณต๊ฐํค e
d=find_d(phi,e) # ๊ฐ์ธํค d
return n, e, d
# ์ํธํ ๋ฐ ๋ณตํธํ
def get_mod(message, exp, n):
result = message
for i in range(1, exp):
#result=(result*message)%n
result=(message**exp)%n
return result
def encrypt(message, e, n):
return get_mod(message, e, n)
def decrypt(message, d, n):
return get_mod(message, d, n)
def main():
message: int = int(input('์ํธํํ ์ซ์๋ฅผ ์
๋ ฅํ์ธ์:'))
#message: int=6
n, e, d = generate_keys()
print('๊ณต๊ฐํค : ',n, e,'๊ฐ์ธํค : ', d)
encrypted = encrypt(message, e, n)
print(' ์ํธํ ๋ ์ซ์ : ', encrypted)
decrypted = decrypt(encrypted, d, n)
print(' ๋ณตํธํ ๋ ์ซ์ : ', decrypted)
if __name__=='__main__':
main()
์์ธ์ง ์ ๋ ฅ ๊ฐ์ด๋ ๋ณตํธํ ๊ฐ์ด ๋ฌ๋ผ์ RSA ์๊ณ ๋ฆฌ์ฆ์ ๊ธฐ๋ฐ์ผ๋ก ์ฝ๋ ์์ ํ๋ค. (๋๊ธ์๋์์ผ๋ฉด ๋ชฐ๋์)
ํด๋น ์ฃผ์ ๋ถ๋ถ์ด ์์ ์ , ์ฃผ์์ด ์๋ผ์๋ ๋ถ๋ถ์ด ์์ ํ ์ด๋ค.
์์ ํ ์ ์ ์๋ ํ์ธ ๊ฐ๋ฅ
๋ฐ์ํ