Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/pskc/encryption.py
blob: d98871a87fb7b48d797f915d0dac3feb42faab9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# encryption.py - module for handling encrypted values
# coding: utf-8
#
# Copyright (C) 2014 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import base64

from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2


AES128_CBC = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc'


class EncryptedValue(object):
    """Wrapper class to handle encrypted values.

    Instances of this class provide the following attributes:

      algorithm: name of the encryption algorithm used
      cipher_value: binary encrypted data
    """

    def __init__(self, encryption, encrypted_value=None):
        """Initialise an encrypted value for the provided Key."""
        self.algorithm = None
        self.cipher_value = None
        self.encryption = encryption
        self.parse(encrypted_value)

    def parse(self, encrypted_value):
        """Read encrypted data from the EncryptedValue XML tree."""
        from pskc.parse import g_e_v, namespaces
        if encrypted_value is None:
            return
        encryption_method = encrypted_value.find(
            'xenc:EncryptionMethod', namespaces=namespaces)
        self.algorithm = encryption_method.attrib.get('Algorithm')
        value = g_e_v(encrypted_value, 'xenc:CipherData/xenc:CipherValue')
        if value is not None:
            self.cipher_value = base64.b64decode(value)

    def decrypt(self):
        """Decrypt the linked value and return the plaintext value."""
        key = self.encryption.key
        ciphertext = self.cipher_value
        if key is None or ciphertext is None:
            return
        if self.algorithm == AES128_CBC:
            iv = ciphertext[:AES.block_size]
            cipher = AES.new(key, AES.MODE_CBC, iv)
            plaintext = cipher.decrypt(ciphertext[AES.block_size:])
            return plaintext[0:-ord(plaintext[-1])]


PBKDF2_URIS = [
    'http://www.rsasecurity.com/rsalabs/pkcs/schemas/pkcs-5#pbkdf2',
    'http://www.rsasecurity.com/rsalabs/pkcs/schemas/pkcs-5v2-0#pbkdf2',
    'http://www.w3.org/2009/xmlenc11#pbkdf2',
]


class KeyDerivation(object):
    """Handle derived keys."""

    def __init__(self, key_deriviation=None):
        self.algorithm = None
        # PBKDF2 properties
        self.pbkdf2_salt = None
        self.pbkdf2_iterations = None
        self.pbkdf2_key_length = None
        self.pbkdf2_prf = None
        self.parse(key_deriviation)

    def parse(self, key_deriviation):
        from pskc.parse import g_e_v, g_e_i, namespaces
        if key_deriviation is None:
            return
        self.algorithm = key_deriviation.attrib.get('Algorithm')
        # PBKDF2 properties
        pbkdf2 = key_deriviation.find(
            'xenc11:PBKDF2-params', namespaces=namespaces)
        if pbkdf2 is None:
            pbkdf2 = key_deriviation.find(
                'pkcs5:PBKDF2-params', namespaces=namespaces)
        if pbkdf2 is not None:
            # get used salt
            value = g_e_v(pbkdf2, 'Salt/Specified')
            if value is not None:
                self.pbkdf2_salt = base64.b64decode(value)
            # required number of iterations
            self.pbkdf2_iterations = g_e_i(pbkdf2, 'IterationCount')
            # key length
            self.pbkdf2_key_length = g_e_i(pbkdf2, 'KeyLength')
            # pseudorandom function used
            prf = pbkdf2.find('PRF', namespaces=namespaces)
            if prf is not None:
                self.pbkdf2_prf = prf.attrib.get('Algorithm')

    def generate(self, password):
        if self.algorithm in PBKDF2_URIS:
            # TODO: support pseudorandom function (prf)
            return PBKDF2(
                password, self.pbkdf2_salt, dkLen=self.pbkdf2_key_length,
                count=self.pbkdf2_iterations, prf=None)


class Encryption(object):
    """Class for handling encryption keys that are used in the PSKC file."""

    def __init__(self, key_info=None):
        self.id = None
        self.key_names = []
        self.key = None
        self.derivation = KeyDerivation()
        self.parse(key_info)

    def parse(self, key_info):
        """Read encryption information from the EncryptionKey XML tree."""
        from pskc.parse import g_e_v, namespaces
        if key_info is None:
            return
        self.id = key_info.attrib.get('Id')
        for name in key_info.findall('ds:KeyName', namespaces=namespaces):
            self.key_names.append(g_e_v(name, '.'))
        for name in key_info.findall(
                'xenc11:DerivedKey/xenc11:MasterKeyName',
                namespaces=namespaces):
            self.key_names.append(g_e_v(name, '.'))
        self.derivation.parse(key_info.find(
            'xenc11:DerivedKey/xenc11:KeyDerivationMethod',
            namespaces=namespaces))

    @property
    def key_name(self):
        if self.key_names:
            return self.key_names[0]

    def derive_key(self, password):
        self.key = self.derivation.generate(password)