-
[Python] 패스워드를 이용한 암호화/복호화Python 2024. 3. 28. 21:02728x90반응형
이번에 데이터베이스를 간단하게 encryption/decryption을 하려하는데 패스워드로 하는 방향으로나와
패스워드를 이용하여 암호화/복호화 코드를 올리려한다. (Encryption/decryption using password)
암호화/복호화 코드는 다음과같다.
import base64 import cryptography from cryptography.hazmat.primitives import hashes from cryptography.fernet import Fernet from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC def encrypt(filename, password): with open(filename, "rb") as file: file_data = file.read() file.close() num_bytes = bytes(password,"utf-8") salt = bytes(16) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=480000, ) key = base64.urlsafe_b64encode(kdf.derive(num_bytes)) f = Fernet(key) encrypted_data = f.encrypt(file_data) with open(filename, "wb") as file: file.write(encrypted_data) file.close() def decrypt(filename, password): num_bytes = bytes(password,"utf-8") salt = bytes(16) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=480000, ) key = base64.urlsafe_b64encode(kdf.derive(num_bytes)) f = Fernet(key) with open(filename, "rb") as file: # read the encrypted data encrypted_data = file.read() file.close() # decrypt data try: decrypted_data = f.decrypt(encrypted_data) except cryptography.fernet.InvalidToken: print("Invalid token, most likely the password is incorrect") return print("File decrypted successfully") with open(filename, "wb") as file: file.write(decrypted_data) file.close() return decrypted_data여기서 기본적으로 패스워드는 터미널에서 입력값으로 넣어준다는 가정. 즉, string으로 받아질테니 password의 인풋만 잘주면된다.
그리고 여기에 salt라는 개념이 또 들어가는데 이 salt는
https://en.wikipedia.org/wiki/Salt_(cryptography)
Salt (cryptography) - Wikipedia
From Wikipedia, the free encyclopedia Random data used as an additional input to a hash function In cryptography, a salt is random data fed as an additional input to a one-way function that hashes data, a password or passphrase.[1] Salting helps defend aga
en.wikipedia.org
위키피디아를 한 번 보고오길 바라는데 어찌됐건 공격을 더 잘 방어하기위해 만들었지만 이 데이터를 어딘가에 보관해야하고 뭐 데이터베이스의 앞에 인덱스를주고 붙여도 되지만 약식으로만 필요했기에 필자는 위의 코드에서 전부 0바이트로 주었다.
그렇게 실험으로 자신의 데이터파일을 붙여서 저 함수를 이용해보면 아마 될것이다.
그럼 이만~!
728x90반응형'Python' 카테고리의 다른 글
[Python] 14502 Baekjoon (1) 2024.10.09 [Python] 16236 Baekjoon (0) 2024.10.02 Window Pyinstaller error '파일에 바이러스 또는 기타 사용자 동의없이 설치된 소프트웨어가 있기 때문에 작업이 완료되지 않았습니다' (0) 2024.01.05 [Python] HMAC SHA256 sign 및 verify (0) 2023.10.28 [Python] AES CBC모드 암호화 및 복호화 (0) 2023.10.28