๐Ÿ— Bcrypt

Min-Ho Leeยท2020๋…„ 7์›” 16์ผ
1

Security

๋ชฉ๋ก ๋ณด๊ธฐ
2/3
post-thumbnail

Thursday_July_16
.
.
.
์ธ์ฆ๊ณผ ์ธ๊ฐ€๋Š” ํ•œ์ชฝ ์ธก๋ฉด์—์„œ ๋‹ด๋‹นํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ
'ํ”„๋ก ํŠธ์—”๋“œ'์™€ '๋ฐฑ์—”๋“œ' ๊ฐ„์˜ ์ƒํ˜ธ ์ž‘์šฉ์ด๋ผ๊ณ  ํ•œ๋‹ค.

๊ทธ ์ค‘์—์„œ '๋ฐฑ์—”๋“œ' ์ธก๋ฉด์—์„œ์˜ ์ธ์ฆ๊ณผ ์ธ๊ฐ€๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ๊ธ€์ด๋‹ค.

1๏ธโƒฃ Bcrypt

๊ตฌํ˜„ํ•˜๊ธฐ ์ „, ๋จผ์ € ๊ฐœ์ธ์ •๋ณด๋ฅผ ํ•„์ˆ˜์ ์œผ๋กœ ๋ณดํ˜ธํ•˜๊ธฐ ์œ„ํ•ด '๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”'๋ฅผ ํ•ด์•ผํ•œ๋‹ค.
์ด ๊ธ€์—์„œ๋Š” ์•”ํ˜ธํ™”๋ฅผ ์œ„ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ Bcrypt๋ฅผ ์„ค์น˜ ํ•  ์˜ˆ์ •์ด๋‹ค.

์„ค์น˜ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

pip install bcrypt 

์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

import bcrypt

์ด๋ ‡๊ฒŒ import๋ฅผ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

๐Ÿง ์ง‘์ค‘!

Bcrypt๋Š” 'str'๋ฐ์ดํ„ฐ๊ฐ€ ์•„๋‹Œ 'bytes' ๋ฐ์ดํ„ฐ๋ฅผ ์•”ํ˜ธํ™” ํ•œ๋‹ค.
๊ทธ ๋ง์€ ์ฆ‰, ์•”ํ˜ธํ™”๋ฅผ ํ•˜๊ณ ์‹ถ๋‹ค๋ฉด 'bytes' ํ˜•ํƒœ๋กœ ๋งŒ๋“ค์–ด ์ค˜์•ผ ์•”ํ˜ธํ™”๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๋ง์ด๋‹ค.

ํ•˜์ง€๋งŒ ๊ฑฑ์ •ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค. ํŒŒ์ด์ฌ์—์„œ๋Š”
'str'์„ encode ํ•˜๋ฉด 'bytes'๊ฐ€ ๋˜๊ณ ,
'bytes'๋ฅผ decode 'str'๊ฐ€ ๋œ๋‹ค.

encode, decode๋ฅผ ํ•  ๋•Œ๋Š”, ์šฐ๋ฆฌ๊ฐ€ ์ธ์‹ํ•  ์ˆ˜ ์žˆ๋„๋ก
ํ˜•ํƒœ๋ฅผ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด 'UTF-8' ์œ ๋‹ˆ์ฝ”๋“œ ๋ฌธ์ž ๊ทœ๊ฒฉ์„ ์‚ฌ์šฉํ•œ๋‹ค.

์ž ๊ทธ๋Ÿผ password๋ฅผ ์•”ํ˜ธํ™” ํ•ด๋ณด์ž.

password = '1234'
hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt())
print(type(hashed_password))
print(hashed_password)

๊ฒฐ๊ณผ๊ฐ’

<class 'bytes'>
b'$2b$12$tUcszX4gTh4QnLqmogi4SeUTjWbJ4graSXdtvyBss//AXM9.A9bDy'

ํƒ€์ž…์€ 'bytes' ํƒ€์ž…์ด๊ณ 
์•”ํ˜ธํ™”๋„ ์ž˜ ๋˜์—ˆ๋‹ค.

์ด ๋ฐฉ์‹์€ '์ผ๋ฐฉํ–ฅ' ์•”ํ˜ธํ™”, ์ฆ‰ ๋ณตํ˜ธํ™”๋ฅผ ํ•  ์ˆ˜ ์—†๋„๋ก ์•”ํ˜ธํ™”๋ฅผ ํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค.
๊ทธ๋Ÿผ ํ”„๋ก ํŠธ์ชฝ์—์„œ ๋ฐ›์€ ๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ์–ด๋–ป๊ฒŒ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?

๊ทธ๊ฒƒ ๋˜ํ•œ bcrypt๊ฐ€ ์ง€์›์„ ํ•ด์ค๋‹ˆ๋‹ค ๐Ÿคฉ

bcrypt์—๋Š” checkpw() ๋ผ๋Š” ํ•จ์ˆ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.
์˜ˆ์ œ๋ฅผ ํ†ตํ•ด ์•Œ์•„๋ด…์‹œ๋‹ค.

bring_password = '1234'
a = bcrypt.checkpw(bring_password.encode('UTF-8'), hashed_password)
print(a)

๊ฒฐ๊ณผ๊ฐ’

True

์ด checkpw() ํ•จ์ˆ˜์˜

์ฒซ ๋ฒˆ์งธ argument = ์ž…๋ ฅ๋ฐ›์€ ํŒจ์Šค์›Œ๋“œ
๋‘ ๋ฒˆ์งธ argument = ์ €์žฅ๋œ ์•”ํ˜ธํ™”๋œ ํŒจ์Šค์›Œ๋“œ

์ด์–ด์•ผ ํ•˜๊ณ , ๋ชจ๋‘ ํƒ€์ž…์€ 'bytes'์—ฌ์•ผ ํ•œ๋‹ค.

profile
๐Ÿ‡ Rabbit can take a rest, but ๐Ÿข turtle can't

0๊ฐœ์˜ ๋Œ“๊ธ€