1
|
from src.dao.private_key_repository import PrivateKeyRepository
|
2
|
from src.model.private_key import PrivateKey
|
3
|
from src.services.cryptography import CryptographyService
|
4
|
|
5
|
|
6
|
class KeyService:
|
7
|
|
8
|
def __init__(self, cryptography_service: CryptographyService, private_key_repository: PrivateKeyRepository):
|
9
|
self.cryptography_service = cryptography_service
|
10
|
self.private_key_repository = private_key_repository
|
11
|
|
12
|
def create_new_key(self, passphrase="") -> PrivateKey:
|
13
|
"""
|
14
|
Creates a new private key using the given passphrase.
|
15
|
:param passphrase: Passphrase to be used when encrypting the PK
|
16
|
:return: An instance of the <PrivateKey> class representing the generated PK
|
17
|
"""
|
18
|
# generate a new private key
|
19
|
private_key_pem = self.cryptography_service.create_private_key(passphrase)
|
20
|
|
21
|
# store generated PK and the passphrase in a wrapper
|
22
|
private_key = PrivateKey(-1, private_key_pem, passphrase)
|
23
|
|
24
|
# store the wrapper in the PK repository
|
25
|
private_key_id = self.private_key_repository.create(private_key)
|
26
|
|
27
|
# assign the generated ID to the wrapper
|
28
|
private_key.private_key_id = private_key_id
|
29
|
|
30
|
return private_key
|
31
|
|
32
|
def get_key(self, unique_id):
|
33
|
"""
|
34
|
Tries to fetch a PK using the given ID.
|
35
|
:param unique_id: ID of the PK to be found
|
36
|
:return:An instance of the required PK or `None`
|
37
|
"""
|
38
|
return self.private_key_repository.read(unique_id)
|
39
|
|
40
|
def get_keys(self, unique_ids=None):
|
41
|
"""
|
42
|
Tries to fetch all PKs in the repository. Exact PKs to be fetched can be specified using the `unique_ids`
|
43
|
parameter. If `unique_ids` parameter is not passed then all PKs in the repository are returned.
|
44
|
:param unique_ids: An array containing IDs of PKs to be fetched from the repository.
|
45
|
:return: A list of instances of the PrivateKey class representing the PKs found
|
46
|
"""
|
47
|
if unique_ids is None:
|
48
|
return self.private_key_repository.read_all()
|
49
|
else:
|
50
|
# TODO this is very inefficient
|
51
|
return [self.private_key_repository.read(identifier) for identifier in unique_ids]
|
52
|
|
53
|
def delete_key(self, unique_id):
|
54
|
"""
|
55
|
Deletes a private key
|
56
|
|
57
|
:param unique_id: ID of specific certificate to be deleted
|
58
|
:return: `True` when the deletion was successful. `False` in other case
|
59
|
"""
|
60
|
return self.private_key_repository.delete(unique_id)
|