๐Ÿ“  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 ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์ฝ”๋“œ ์ˆ˜์ •ํ–ˆ๋‹ค. (๋Œ“๊ธ€์•„๋‹ˆ์—ˆ์œผ๋ฉด ๋ชฐ๋ž์Œ)

ํ•ด๋‹น ์ฃผ์„ ๋ถ€๋ถ„์ด ์ˆ˜์ • ์ „ , ์ฃผ์„์ด ์•ˆ๋ผ์žˆ๋Š” ๋ถ€๋ถ„์ด ์ˆ˜์ •ํ›„ ์ด๋‹ค. 

์ˆ˜์ • ํ›„ ์ •์ƒ ์ž‘๋™ ํ™•์ธ ๊ฐ€๋Šฅ

 

 

ํŒŒ์ด์ฌ, RSA ์•”ํ˜ธํ™”

๋”๋ณด๊ธฐ ๋Œ€์นญํ‚ค ์•”ํ˜ธํ™” ์ผ๋ฐ˜์ ์œผ๋กœ ์•”ํ˜ธ๋ผ๊ณ  ํ•˜๋ฉด ๋– ์˜ฌ๋ฆฌ๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค. ์•”ํ˜ธ๋ฌธ์„ ์ƒ์„ฑํ•  ๋•Œ, ๋ณต์›ํ•  ๋•Œ ๊ฐ™์€ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋‚œ์ˆ˜ํ‘œ๋‚˜ ์‹œ์ € ์•”ํ˜ธ๋„ ๋Œ€์นญํ‚ค ์•”ํ˜ธํ™”์ฃ . ์žฅ์ ์€ ๋‹จ์ˆœํ•˜๊ธฐ ๋•Œ๋ฌธ์—

comdoc.tistory.com

 

๋ฐ˜์‘ํ˜•