.
This commit is contained in:
17
CS1032/lecture-2023-11-23/crypt.py
Normal file
17
CS1032/lecture-2023-11-23/crypt.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from hashlib import sha256
|
||||
from itertools import cycle
|
||||
import base64
|
||||
|
||||
def crypt(msg: bytes, key: str) -> bytes:
|
||||
key_h = sha256()
|
||||
key_h.update(key.encode('utf8'))
|
||||
key = key_h.digest()
|
||||
|
||||
return bytes(p ^ k for (p, k) in zip(msg, cycle(key)))
|
||||
|
||||
def encrypt(msg: str, key: str) -> str:
|
||||
return base64.b64encode(crypt(bytes(msg, 'utf8'), key)).decode('utf8')
|
||||
|
||||
def decrypt(msg: str, key: str) -> str:
|
||||
return crypt(base64.b64decode(msg), key).decode('utf8')
|
||||
|
||||
Reference in New Issue
Block a user