๐Ÿ“  Secure/๐Ÿ†” Crypto

[Crypto] Python | RSA ์•”ํ˜ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌ์ถ•

sa1t 2023. 9. 11. 22:51
๋ฐ˜์‘ํ˜•

from Crypto.Util.number import getPrime
from gmpy2 import invert

# ํŒŒ์ด์ฌ์—์„œ p, q ๊ฐ’์„ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•
p = getPrime(1024) #1024 bit / ๋ฌด์ž‘์œ„๋กœ ํฐ ๋‘ ์†Œ์ˆ˜ p, q ๊ณ ๋ฅด๊ธฐ
q = getPrime(1024)

# n ๊ฐ’ ๊ณ„์‚ฐํ•˜๋Š” ๋ฒ•
n = p * q

# n ์ดํ•˜์˜ n๊ณผ ์„œ๋กœ์†Œ์ธ ์ˆ˜๋“ค์˜ ๊ฐœ์ˆ˜ ๊ณ„์‚ฐ
phi = (p - 1) * (q - 1)

# 1<e<phi ์ด๊ณ , e์™€ phi๊ฐ€ ์„œ๋กœ์†Œ์ธ e๋ฅผ ์„ ํƒ ( ๋Œ€๊ฐœ 65537 ์‚ฌ์šฉ )
e=65537

# de=1(mod phi)๋ฅผ ๋งŒ์กฑํ•˜๋Š” d๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค / ์ž„์˜์˜ ์ •์ˆ˜ k์— ๋Œ€ํ•ด์„œ de=1+k phi๋ฅผ ๋งŒ์กฑ
d= invert(e,phi)

print("๊ณต๊ฐœํ‚ค n = ",n)
print("๊ณต๊ฐœํ‚ค e = ",e)
print("๊ฐœ์ธํ‚ค d = ",d)

์•”ํ˜ธํ™”์™€ ๋ณตํ˜ธํ™”

# ์•”ํ˜ธํ™”
# ์›๋ณธ ๋ฉ”์‹œ์ง€ m, ์•”ํ˜ธํ™”๋œ ๋ฉ”์‹œ์ง€ M, ๊ณต๊ฐœํ‚ค e,n , ๊ฐœ์ธํ‚ค d
m=11

# ์•”ํ˜ธํ™” ๋œ ๋ฉ”์‹œ์ง€ = ์›๋ณธ ๋ฉ”์‹œ์ง€ ** ๊ณต๊ฐœํ‚คe % ๊ณต๊ฐœํ‚คn
M = m**e%n
print("์•”ํ˜ธํ™” ๋œ ๋ฉ”์‹œ์ง€ = ",M)

# ์›๋ณธ ๋ฉ”์‹œ์ง€ = ์•”ํ˜ธํ™” ๋œ ๋ฉ”์‹œ์ง€ ** ๊ฐœ์ธํ‚ค d % ๊ณต๊ฐœํ‚คn
# ๋ณตํ˜ธํ™”
m = M**d%n
print(" ๋ณตํ˜ธํ™” ๋œ ๋ฉ”์‹œ์ง€n = ",m)
๋ฐ˜์‘ํ˜•