๐Ÿ“  Secure/๐Ÿ†” Crypto

[Crypto] RSA ํŒŒ์ด์ฌ ์ฝ”๋“œ ๋ฐ ๊ฐœ๋…

sa1t 2023. 9. 4. 13:52
๋ฐ˜์‘ํ˜•
RSA ๊ณต๊ฐœํ‚ค ๊ฐœ์ธํ‚ค ๊ตฌํ•˜๋Š”๋ฒ•

 

1. p ๊ฐ’, q๊ฐ’ ์ƒ์„ฑ ( ๋ฌด์ž‘์œ„๋กœ ํฐ ๋‘ ์†Œ์ˆ˜๋ฅผ ์„ ํƒ )

# ํŒŒ์ด์ฌ์—์„œ p, q ๊ฐ’์„ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•
from Crypto.Util.number import getPrime

p = getPrime(1024) #1024 = 1024bit๋ฅผ ์˜๋ฏธ
q = getPrime(1024)

pycryptodome์ด ์„ค์น˜๋˜์–ด ์žˆ์ง€ ์•Š์„ ๊ฒฝ์šฐ

# pycryptodome ์„ค์น˜๋˜์–ด์žˆ์ง€ ์•Š์„ ์‹œ ์„ค์น˜๋ฒ•
$ pip install pycryptodome

2. n ๊ณ„์‚ฐ

p์™€ q๋ฅผ ๊ณฑํ•˜๋ฉด n์ด ๋œ๋‹ค.

n = p * q

 

 

3. phi ๊ณ„์‚ฐ

(p-1)๊ณผ (q-1)์„ ๊ณฑํ•˜๋ฉด phi๊ฐ€ ๋œ๋‹ค.

*phi = n์ดํ•˜์˜ n๊ณผ ์„œ๋กœ์†Œ์ธ ์ˆ˜๋“ค์˜ ๊ฐœ์ˆ˜

phi = (p-1) * (q-1)

 

4. e ์„ ํƒ

์ฃผ๋กœ 65537

๋‹ค๋ฅธ ๊ฐ’์ด ๋˜๋”๋ผ๋„ 1<e<phi์ด๊ณ  phi์™€ ์„œ๋กœ์†Œ์ธ ์ˆ˜๋กœ ์„ ํƒ

 

 

5. d ๊ณ„์‚ฐ

mod phi์— ๋Œ€ํ•œ e์˜ ๊ณฑ์…ˆ์˜ ์—ญ์›์„ ๊ตฌํ•œ๋‹ค.

de=1(mod phi)๋ฅผ ๋งŒ์กฑํ•˜๋Š” d๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.

์ฆ‰, ์ž„์˜์˜ ์ •์ˆ˜ k์— ๋Œ€ํ•ด์„œ ๋‹ค์Œ์„ ๋งŒ์กฑํ•  ๊ฒƒ

de=1+k(phi)

# gmpy2์˜ invert๋‚˜ divm์œผ๋กœ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ๋‹ค.
d = invert(e, phi)
d = divm(1, e, phi)
# invert = ๋ฐ”๋กœ ๊ณฑ์…ˆ์˜ ์—ญ์›์„ ๊ตฌํ•ด์ค€๋‹ค
# divm = ์ฒซ๋ฒˆ์งธ ์ธ์ž๋ฅผ 1๋กœ ์ง€์ •ํ•ด์ฃผ๋ฉด ์—ญ์›์„ ๊ตฌํ•ด์ค€๋‹ค.

gmpy2 ์„ค์น˜๋ฒ• *์ถ”ํ›„ ๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ๊ธ€๋กœ ๋ณ€๊ฒฝํ•  ์˜ˆ์ •

https://domdom.tistory.com/169

 

[Python3] ๋ฆฌ๋ˆ…์Šค/Windows์—์„œ python gmpy, gmpy2 ์„ค์น˜ ๋ฐฉ๋ฒ•

Linux ๊ณ„์—ด ์šด์˜์ฒด์ œ์˜ ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ช…๋ น์–ด๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ์„ค์น˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. sudo apt-get install libgmp3-dev sudo apt-get install libmpfr-dev sudo apt-get install libmpc-dev sudo pip3 install gmpy sudo pip3 install gmpy2 Wind

domdom.tistory.com

 

6. ๊ฒฐ๊ณผ

๊ณต๊ฐœํ‚ค: (e, n)

๊ฐœ์ธํ‚ค: (d, n)


RSA ์•”ํ˜ธํ™” ๋ฐ ๋ณตํ˜ธํ™”

์•”ํ˜ธํ™”

์•”ํ˜ธ๋ฌธ = ํ‰๋ฌธ^e mod n

 

๋ณตํ˜ธํ™”

๋ณตํ˜ธ๋ฌธ = ์•”ํ˜ธ๋ฌธ^d mod n

๋ฐ˜์‘ํ˜•