-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.py
33 lines (27 loc) · 1.07 KB
/
crypto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# PrivateVoice
# https://github.com/Duck1776/PrivateVoice
# crypto.py
# UPDATES
# Separated the code into sections on seperate files
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def generate_key():
return os.urandom(32).hex()
class ChaCha20Cipher:
def __init__(self, key):
self.key = bytes.fromhex(key)
self.nonce_size = 16 # in bytes
def encrypt(self, data):
nonce = os.urandom(self.nonce_size)
cipher = Cipher(algorithms.ChaCha20(self.key, nonce), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
encrypted_data = nonce + encryptor.update(data)
return encrypted_data
def decrypt(self, data):
nonce = data[:self.nonce_size]
ciphertext = data[self.nonce_size:]
cipher = Cipher(algorithms.ChaCha20(self.key, nonce), mode=None, backend=default_backend())
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(ciphertext)
return decrypted_data