]> git.datanom.net - securemail.git/blobdiff - cryptonize.py
Make backwards compatible with nacl 1.0.x
[securemail.git] / cryptonize.py
index 9cc463120804f83d6a7295b4565107d609748d3b..d24a72ba20b3a2fa71a2ea8f333e297463e96403 100644 (file)
 # You should have received a copy of the GNU General Public License
 # along with SecureMail.  If not, see <https://www.gnu.org/licenses/>.
 
+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,7 +45,7 @@ class Cryptonize:
         skey = self.sanitize_key(key)
         box = SecretBox(skey)
         plain = box.decrypt(cipher)
-        box = None
+        box = skey = None
         
         return plain
         
@@ -66,14 +71,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 +95,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)
This page took 0.030554 seconds and 5 git commands to generate.