]>
git.datanom.net - securemail.git/blob - cryptonize.py
1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2018 Michael Rasmussen <mir@datanom.net>
5 # This file is part of SecureMail.
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.
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.
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/>.
20 from nacl
import __version__
as NACL_VERSION
21 from nacl
.secret
import SecretBox
22 from nacl
.public
import PrivateKey
, Box
23 from nacl
.utils
import random
, EncryptedMessage
24 from nacl
.encoding
import HexEncoder
29 Encrypt and decrypt objects
32 def symmetric_encrypt(self
, key
, plain
):
33 skey
= self
.sanitize_key(key
)
35 if NACL_VERSION
< "1.1.0":
36 nonce
= random(SecretBox
.NONCE_SIZE
)
37 cipher
= box
.encrypt(plain
, nonce
)
39 cipher
= box
.encrypt(plain
)
44 def symmetric_decrypt(self
, key
, cipher
):
45 skey
= self
.sanitize_key(key
)
47 plain
= box
.decrypt(cipher
)
52 def asymmetric_encrypt(self
, privkey
, pubkey
, plain
):
53 box
= Box(privkey
, pubkey
)
54 if NACL_VERSION
< "1.1.0":
55 nonce
= random(Box
.NONCE_SIZE
)
56 cipher
= box
.encrypt(plain
, nonce
)
58 cipher
= box
.encrypt(plain
)
63 def asymmetric_decrypt(self
, privkey
, pubkey
, cipher
):
64 box
= Box(privkey
, pubkey
)
65 plain
= box
.decrypt(cipher
)
70 def get_random_key(self
):
71 return random(SecretBox
.KEY_SIZE
)
73 def sanitize_key(self
, key
):
74 if not isinstance(key
, bytes
):
75 key
= key
.encode('utf-8')
77 if size
< SecretBox
.KEY_SIZE
:
79 newkey
= key
+ bytes(SecretBox
.KEY_SIZE
- size
)
80 elif size
> SecretBox
.KEY_SIZE
:
81 newkey
= key
[:SecretBox
.KEY_SIZE
]
88 def get_key_pair(self
):
89 privkey
= PrivateKey
.generate()
90 pubkey
= privkey
.public_key
92 return (privkey
, pubkey
)
94 def generate_hash(self
, key
):
95 if not isinstance(key
, bytes
):
96 key
= key
.encode('utf-8')
97 HASHER
= nacl
.hash.sha512
98 digest
= HASHER(key
, encoder
=HexEncoder
)
100 return digest
.decode()
102 def create_EncryptedMessage(self
, payload
):
103 nonce
= payload
[:SecretBox
.NONCE_SIZE
]
104 ciphertext
= payload
[SecretBox
.NONCE_SIZE
:]
106 return EncryptedMessage
._from
_parts
(
107 nonce
, ciphertext
, nonce
+ ciphertext
)
This page took 0.13104 seconds and 6 git commands to generate.