]> git.datanom.net - securemail.git/blame - cryptonize.py
First working beta
[securemail.git] / cryptonize.py
CommitLineData
8c4f590c
MR
1# -*- coding: utf-8 -*-
2
3# Copyright (c) 2018 Michael Rasmussen <mir@datanom.net>
4
5# This file is part of SecureMail.
6
7# SecureMail is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# SecureMail is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with SecureMail. If not, see <https://www.gnu.org/licenses/>.
19
20from nacl.secret import SecretBox
21from nacl.public import PrivateKey, Box
d65fab5a 22from nacl.utils import random, EncryptedMessage
8c4f590c
MR
23from nacl.encoding import HexEncoder
24import nacl.hash
25
26class Cryptonize:
27 """
28 Encrypt and decrypt objects
29 """
30
31 def symmetric_encrypt(self, key, plain):
32 skey = self.sanitize_key(key)
33 box = SecretBox(skey)
34 cipher = box.encrypt(plain)
d65fab5a 35 box = skey = None
8c4f590c
MR
36
37 return cipher
38
39 def symmetric_decrypt(self, key, cipher):
40 skey = self.sanitize_key(key)
41 box = SecretBox(skey)
42 plain = box.decrypt(cipher)
d65fab5a 43 box = skey = None
8c4f590c
MR
44
45 return plain
46
47 def asymmetric_encrypt(self, privkey, pubkey, plain):
48 box = Box(privkey, pubkey)
49 cipher = box.encrypt(plain)
50 box = None
51
52 return cipher
53
54 def asymmetric_decrypt(self, privkey, pubkey, cipher):
55 box = Box(privkey, pubkey)
56 plain = box.decrypt(cipher)
57 box = None
58
59 return plain
60
61 def get_random_key(self):
62 return random(SecretBox.KEY_SIZE)
63
64 def sanitize_key(self, key):
65 if not isinstance(key, bytes):
66 key = key.encode('utf-8')
67 size = len(key)
68 if size < SecretBox.KEY_SIZE:
d65fab5a
MR
69 """ We must pad """
70 newkey = key + bytes(SecretBox.KEY_SIZE - size)
71 elif size > SecretBox.KEY_SIZE:
72 newkey = key[:SecretBox.KEY_SIZE]
8c4f590c
MR
73 else:
74 newkey = key
75
76
77 return newkey
78
79 def get_key_pair(self):
80 privkey = PrivateKey.generate()
81 pubkey = privkey.public_key
82
83 return (privkey, pubkey)
84
85 def generate_hash(self, key):
86 if not isinstance(key, bytes):
87 key = key.encode('utf-8')
88 HASHER = nacl.hash.sha512
89 digest = HASHER(key, encoder=HexEncoder)
90
91 return digest.decode()
92
d65fab5a
MR
93 def create_EncryptedMessage(self, payload):
94 nonce = payload[:SecretBox.NONCE_SIZE]
95 ciphertext = payload[SecretBox.NONCE_SIZE:]
8c4f590c 96
d65fab5a
MR
97 return EncryptedMessage._from_parts(
98 nonce, ciphertext, nonce + ciphertext)
This page took 0.040649 seconds and 5 git commands to generate.