X-Git-Url: http://git.datanom.net/securemail.git/blobdiff_plain/8c4f590c61472aa754a180e918ca5de7d1af5ad6..462ce28c82250dc813e30999254e8bcbbfd4883d:/cryptonize.py?ds=sidebyside diff --git a/cryptonize.py b/cryptonize.py index 9cc4631..7a598d3 100644 --- a/cryptonize.py +++ b/cryptonize.py @@ -17,9 +17,10 @@ # You should have received a copy of the GNU General Public License # along with SecureMail. If not, see . +from nacl import __version__ as NACL_VERSION from nacl.secret import SecretBox from nacl.public import PrivateKey, Box -from nacl.utils import random +from nacl.utils import random, EncryptedMessage from nacl.encoding import HexEncoder import nacl.hash @@ -31,8 +32,12 @@ class Cryptonize: def symmetric_encrypt(self, key, plain): skey = self.sanitize_key(key) box = SecretBox(skey) - cipher = box.encrypt(plain) - box = None + if NACL_VERSION < "1.1.0": + nonce = random(SecretBox.NONCE_SIZE) + cipher = box.encrypt(plain, nonce) + else: + cipher = box.encrypt(plain) + box = skey = None return cipher @@ -40,18 +45,26 @@ class Cryptonize: skey = self.sanitize_key(key) box = SecretBox(skey) plain = box.decrypt(cipher) - box = None + box = skey = None return plain def asymmetric_encrypt(self, privkey, pubkey, plain): + if not isinstance(plain, bytes): + plain = plain.encode('utf-8') box = Box(privkey, pubkey) - cipher = box.encrypt(plain) + if NACL_VERSION < "1.1.0": + nonce = random(Box.NONCE_SIZE) + cipher = box.encrypt(plain, nonce) + else: + cipher = box.encrypt(plain) box = None return cipher def asymmetric_decrypt(self, privkey, pubkey, cipher): + if not isinstance(cipher, bytes): + cipher = cipher.encode('utf-8') box = Box(privkey, pubkey) plain = box.decrypt(cipher) box = None @@ -66,14 +79,10 @@ class Cryptonize: key = key.encode('utf-8') size = len(key) if size < SecretBox.KEY_SIZE: - """We must pad""" - pad = None - for i in range(SecretBox.KEY_SIZE - size): - if pad is None: - pad = b'\0' - else: - pad += b'\0' - newkey = key + pad + """ We must pad """ + newkey = key + bytes(SecretBox.KEY_SIZE - size) + elif size > SecretBox.KEY_SIZE: + newkey = key[:SecretBox.KEY_SIZE] else: newkey = key @@ -94,4 +103,9 @@ class Cryptonize: return digest.decode() + def create_EncryptedMessage(self, payload): + nonce = payload[:SecretBox.NONCE_SIZE] + ciphertext = payload[SecretBox.NONCE_SIZE:] + return EncryptedMessage._from_parts( + nonce, ciphertext, nonce + ciphertext)