def gcd(a, b):
while b!=0:
a, b = b, a%b
return a
def decrypt(pk, ciphertext):
#Unpack the key into its components
key, n = pk
#Generate the plaintext based on the ciphertext and key using a^b mod m
plain = [chr((char ** key) % n) for char in ciphertext]
#Return the array of bytes as a string
return ''.join(plain)
def encrypt(pk, plaintext):
#Unpack the key into it's components
key, n = pk
#Convert each letter in the plaintext to numbers based on the character using a^b mod m
cipher = [(ord(char) ** key) % n for char in plaintext]
#Return the array of bytes
return cipher
def get_private_key(e, tot):
k=1
while (e*k)%tot != 1 or k == e:
k+=1
return k
def get_public_key(tot):
e=2
while e<totient and gcd(e, totient)!=1:
e += 1
return e
# 문자열 입력
m = input("변환 할 문자열을 입력:")
# 두개의 소수 설정
p = 4733
q = 1103
#print("Two prime numbers(p and q) are:", str(p), "and", str(q))
# 두소수의 계수 구하기
n = p*q
#print("n(p*q)=", str(p), "*", str(q), "=", str(n))
# 피함수 값 totient 구하기
totient = (p-1)*(q-1)
#print("(p-1)*(q-1)=", str(totient))
# 공개키 값 구하기
e = get_public_key(totient)
#print("공개키 (n, e):("+str(n)+","+str(e)+")")
# 개인키 값 구하기
d = get_private_key(e, totient)
#print("개인키 (n, d):("+str(n)+","+str(d)+")")
# Encrypt message
encrypted_msg = encrypt((e,n), m)
print('암호화된 메세지 :', ''.join(map(lambda x: str(x), encrypted_msg)))
# Decrypt message
print('복호화된 메세지 :', decrypt((d,n),encrypted_msg))
반응형
'코딩 > Python' 카테고리의 다른 글
파이썬으로 slack 봇 만들기(pt.2) (0) | 2021.01.24 |
---|---|
파이썬으로 slack 봇 만들기(pt.1) (0) | 2021.01.18 |
flask로 get 요청 처리하기 (0) | 2021.01.14 |
파이썬 flask 기초 (0) | 2020.12.24 |
공룡 게임 자동으로 클리어하기 (0) | 2020.11.16 |