2020-10-28 11:50:14 +01:00
|
|
|
import os
|
2020-04-02 21:29:16 +02:00
|
|
|
from io import BytesIO
|
|
|
|
|
2020-10-28 11:50:14 +01:00
|
|
|
import pgpy
|
|
|
|
from pgpy import PGPMessage
|
2020-03-08 12:51:33 +01:00
|
|
|
|
2020-10-28 11:50:14 +01:00
|
|
|
from app.config import ROOT_DIR
|
|
|
|
from app.pgp_utils import (
|
|
|
|
load_public_key,
|
|
|
|
gpg,
|
|
|
|
encrypt_file,
|
|
|
|
encrypt_file_with_pgpy,
|
2020-11-03 13:30:13 +01:00
|
|
|
sign_data,
|
|
|
|
sign_data_with_pgpy,
|
2020-10-28 11:50:14 +01:00
|
|
|
)
|
2020-03-08 12:51:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
def test_load_public_key():
|
2020-10-28 11:50:14 +01:00
|
|
|
public_key_path = os.path.join(ROOT_DIR, "local_data/public-pgp.asc")
|
|
|
|
public_key = open(public_key_path).read()
|
|
|
|
load_public_key(public_key)
|
2020-03-08 12:51:33 +01:00
|
|
|
assert len(gpg.list_keys()) == 1
|
|
|
|
|
|
|
|
|
|
|
|
def test_encrypt():
|
2020-10-28 11:50:14 +01:00
|
|
|
public_key_path = os.path.join(ROOT_DIR, "local_data/public-pgp.asc")
|
|
|
|
public_key = open(public_key_path).read()
|
|
|
|
fingerprint = load_public_key(public_key)
|
2020-04-02 21:29:16 +02:00
|
|
|
secret = encrypt_file(BytesIO(b"abcd"), fingerprint)
|
2020-03-08 12:51:33 +01:00
|
|
|
assert secret != ""
|
2020-10-28 11:50:14 +01:00
|
|
|
|
|
|
|
|
|
|
|
def test_encrypt_file_with_pgpy():
|
|
|
|
encrypt_decrypt_text("heyhey")
|
|
|
|
encrypt_decrypt_text("👍💪")
|
|
|
|
encrypt_decrypt_text("éèù")
|
|
|
|
encrypt_decrypt_text("片仮名")
|
|
|
|
|
|
|
|
|
|
|
|
def encrypt_decrypt_text(text: str):
|
|
|
|
public_key_path = os.path.join(ROOT_DIR, "local_data/public-pgp.asc")
|
|
|
|
public_key = open(public_key_path).read()
|
|
|
|
|
|
|
|
encrypted: PGPMessage = encrypt_file_with_pgpy(text.encode(), public_key)
|
|
|
|
|
|
|
|
# decrypt
|
|
|
|
private_key_path = os.path.join(ROOT_DIR, "local_data/private-pgp.asc")
|
|
|
|
private_key = open(private_key_path).read()
|
|
|
|
priv = pgpy.PGPKey()
|
|
|
|
priv.parse(private_key)
|
|
|
|
decrypted = priv.decrypt(encrypted).message
|
2023-11-21 16:42:18 +01:00
|
|
|
if isinstance(decrypted, str):
|
2020-10-28 11:50:14 +01:00
|
|
|
assert decrypted == text
|
2023-11-21 16:42:18 +01:00
|
|
|
elif isinstance(decrypted, bytearray):
|
2020-10-28 11:50:14 +01:00
|
|
|
assert decrypted.decode() == text
|
2020-11-03 13:30:13 +01:00
|
|
|
|
|
|
|
|
|
|
|
def test_sign_data():
|
|
|
|
assert sign_data("heyhey")
|
|
|
|
assert sign_data(b"bytes")
|
|
|
|
|
|
|
|
|
|
|
|
def test_sign_data_with_pgpy():
|
|
|
|
assert sign_data_with_pgpy("unicode")
|
|
|
|
assert sign_data_with_pgpy(b"bytes")
|