import nacl.secret
import nacl.utils
from base64 import b64decode, b64encode


def encrypt(plaintext, key):
    box = nacl.secret.SecretBox(key.encode('utf-8'))
    plaintext = plaintext.encode('utf-8')
    nonce = nacl.utils.random(24)
    encrypted = box.encrypt(plaintext, nonce)
    return b64encode(encrypted.nonce).decode('utf-8') + ":" + b64encode(encrypted.ciphertext).decode('utf-8')


def decrypt(ciphertext, key):
    ciphers = ciphertext.split(':')
    nonce = b64decode(ciphers[0].encode('utf-8'))
    text = b64decode(ciphers[1].encode('utf-8'))
    box = nacl.secret.SecretBox(key.encode('utf-8'))
    plaintext = box.decrypt(text, nonce)
    return plaintext.decode('utf-8')


if __name__ == '__main__':
    result = encrypt('phamhongphuc', 'THIS_IS_MY_32_CHARS_SECRET___KEY')
    print(type(result))
    abc = decrypt(result, 'THIS_IS_MY_32_CHARS_SECRET___KEY')
    print(abc)

import nacl.secret
import nacl.utils
from base64 import b64decode, b64encode


def encrypt(plaintext, key):
    box = nacl.secret.SecretBox(key.encode('utf-8'))
    plaintext = plaintext.encode('utf-8')
    nonce = nacl.utils.random(24)
    encrypted = box.encrypt(plaintext, nonce)
    return b64encode(encrypted.nonce).decode('utf-8') + ":" + b64encode(encrypted.ciphertext).decode('utf-8')


def decrypt(ciphertext, key):
    ciphers = ciphertext.split(':')
    nonce = b64decode(ciphers[0].encode('utf-8'))
    text = b64decode(ciphers[1].encode('utf-8'))
    box = nacl.secret.SecretBox(key.encode('utf-8'))
    plaintext = box.decrypt(text, nonce)
    return plaintext.decode('utf-8')


if __name__ == '__main__':
    result = encrypt('phamhongphuc', 'THIS_IS_MY_32_CHARS_SECRET___KEY')
    print(type(result))
    abc = decrypt(result, 'THIS_IS_MY_32_CHARS_SECRET___KEY')
    print(abc)
