mirror of https://github.com/nucypher/nucypher.git
Add symm_encrypt/decrypt methods in KeyRing w/ tests
parent
b3f0335679
commit
b6e18ec085
|
@ -1,5 +1,6 @@
|
|||
import sha3
|
||||
from nacl.utils import random
|
||||
from nacl.secret import SecretBox
|
||||
from nkms.crypto.keypairs import SigningKeypair, EncryptingKeypair
|
||||
from npre import umbral
|
||||
|
||||
|
@ -137,6 +138,32 @@ class KeyRing(object):
|
|||
# TODO: What to do if not enough shares, or invalid?
|
||||
return self.enc_keypair.combine(shares)
|
||||
|
||||
def symm_encrypt(self, key, plaintext):
|
||||
"""
|
||||
Encrypts the plaintext using SecretBox symmetric encryption.
|
||||
|
||||
:param bytes key: Key to encrypt with
|
||||
:param bytes plaintext: Plaintext to encrypt
|
||||
|
||||
:rtype: bytes
|
||||
:return: Ciphertext from SecretBox symmetric encryption
|
||||
"""
|
||||
cipher = SecretBox(key)
|
||||
return cipher.encrypt(plaintext)
|
||||
|
||||
def symm_decrypt(self, key, ciphertext):
|
||||
"""
|
||||
Decrypts the ciphertext using SecretBox symmetric decryption.
|
||||
|
||||
:param bytes key: Key to decrypt with
|
||||
:param bytes ciphertext: Ciphertext from SecretBox encryption
|
||||
|
||||
:rtype: bytes
|
||||
:return: Plaintext from SecretBox decryption
|
||||
"""
|
||||
cipher = SecretBox(key)
|
||||
return cipher.decrypt(ciphertext)
|
||||
|
||||
def secure_random(self, length):
|
||||
"""
|
||||
Generates a bytestring from a secure random source for keys, etc.
|
||||
|
|
|
@ -79,6 +79,23 @@ class TestKeyRing(unittest.TestCase):
|
|||
self.assertEqual(32, len(dec_key))
|
||||
self.assertTrue(dec_key == raw_key)
|
||||
|
||||
def test_symm_encryption(self):
|
||||
key = self.keyring_a.secure_random(32)
|
||||
self.assertEqual(32, len(key))
|
||||
|
||||
ciphertext = self.keyring_a.symm_encrypt(key, self.msg)
|
||||
self.assertTrue(self.msg not in ciphertext)
|
||||
|
||||
def test_symm_decryption(self):
|
||||
key = self.keyring_a.secure_random(32)
|
||||
self.assertEqual(32, len(key))
|
||||
|
||||
ciphertext = self.keyring_a.symm_encrypt(key, self.msg)
|
||||
self.assertTrue(self.msg not in ciphertext)
|
||||
|
||||
plaintext = self.keyring_a.symm_decrypt(key, ciphertext)
|
||||
self.assertTrue(self.msg == plaintext)
|
||||
|
||||
def test_secure_random(self):
|
||||
length = random.randrange(1, 100)
|
||||
rand_bytes = self.keyring_a.secure_random(length)
|
||||
|
|
Loading…
Reference in New Issue