Debian Codegraph @

lib/Crypto/IO/PEM.py

raw symbols SCIP
1 #
2 # Util/PEM.py : Privacy Enhanced Mail utilities
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 __all__ = ['encode', 'decode']
35
36 import re
37 from binascii import a2b_base64, b2a_base64, hexlify, unhexlify
38
39 from Crypto.Hash import MD5
40 from Crypto.Util.Padding import pad, unpad
41 from Crypto.Cipher import DES, DES3, AES
42 from Crypto.Protocol.KDF import PBKDF1
43 from Crypto.Random import get_random_bytes
44 from Crypto.Util.py3compat import tobytes, tostr
45
46
47 def encode(data, marker, passphrase=None, randfunc=None):
48 """Encode a piece of binary data into PEM format.
49
50 Args:
51 data (byte string):
52 The piece of binary data to encode.
53 marker (string):
54 The marker for the PEM block (e.g. "PUBLIC KEY").
55 Note that there is no official master list for all allowed markers.
56 Still, you can refer to the OpenSSL_ source code.
57 passphrase (byte string):
58 If given, the PEM block will be encrypted. The key is derived from
59 the passphrase.
60 randfunc (callable):
61 Random number generation function; it accepts an integer N and returns
62 a byte string of random data, N bytes long. If not given, a new one is
63 instantiated.
64
65 Returns:
66 The PEM block, as a string.
67
68 .. _OpenSSL: https://github.com/openssl/openssl/blob/master/include/openssl/pem.h
69 """
70
71 if randfunc is None:
72 randfunc = get_random_bytes
73
74 out = "-----BEGIN %s-----\n" % marker
75 if passphrase:
76 # We only support 3DES for encryption
77 salt = randfunc(8)
78 key = PBKDF1(passphrase, salt, 16, 1, MD5)
79 key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
80 objenc = DES3.new(key, DES3.MODE_CBC, salt)
81 out += "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n" %\
82 tostr(hexlify(salt).upper())
83 # Encrypt with PKCS#7 padding
84 data = objenc.encrypt(pad(data, objenc.block_size))
85 elif passphrase is not None:
86 raise ValueError("Empty password")
87
88 # Each BASE64 line can take up to 64 characters (=48 bytes of data)
89 # b2a_base64 adds a new line character!
90 chunks = [tostr(b2a_base64(data[i:i + 48]))
91 for i in range(0, len(data), 48)]
92 out += "".join(chunks)
93 out += "-----END %s-----" % marker
94 return out
95
96
97 def _EVP_BytesToKey(data, salt, key_len):
98 d = [ b'' ]
99 m = (key_len + 15 ) // 16
100 for _ in range(m):
101 nd = MD5.new(d[-1] + data + salt).digest()
102 d.append(nd)
103 return b"".join(d)[:key_len]
104
105
106 def decode(pem_data, passphrase=None):
107 """Decode a PEM block into binary.
108
109 Args:
110 pem_data (string):
111 The PEM block.
112 passphrase (byte string):
113 If given and the PEM block is encrypted,
114 the key will be derived from the passphrase.
115
116 Returns:
117 A tuple with the binary data, the marker string, and a boolean to
118 indicate if decryption was performed.
119
120 Raises:
121 ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
122 been provided or if the passphrase is incorrect.
123 """
124
125 # Verify Pre-Encapsulation Boundary
126 r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
127 m = r.match(pem_data)
128 if not m:
129 raise ValueError("Not a valid PEM pre boundary")
130 marker = m.group(1)
131
132 # Verify Post-Encapsulation Boundary
133 r = re.compile(r"-----END (.*)-----\s*$")
134 m = r.search(pem_data)
135 if not m or m.group(1) != marker:
136 raise ValueError("Not a valid PEM post boundary")
137
138 # Removes spaces and slit on lines
139 lines = pem_data.replace(" ", '').split()
140
141 # Decrypts, if necessary
142 if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
143 if not passphrase:
144 raise ValueError("PEM is encrypted, but no passphrase available")
145 DEK = lines[2].split(':')
146 if len(DEK) != 2 or DEK[0] != 'DEK-Info':
147 raise ValueError("PEM encryption format not supported.")
148 algo, salt = DEK[1].split(',')
149 salt = unhexlify(tobytes(salt))
150
151 padding = True
152
153 if algo == "DES-CBC":
154 key = _EVP_BytesToKey(passphrase, salt, 8)
155 objdec = DES.new(key, DES.MODE_CBC, salt)
156 elif algo == "DES-EDE3-CBC":
157 key = _EVP_BytesToKey(passphrase, salt, 24)
158 objdec = DES3.new(key, DES3.MODE_CBC, salt)
159 elif algo == "AES-128-CBC":
160 key = _EVP_BytesToKey(passphrase, salt[:8], 16)
161 objdec = AES.new(key, AES.MODE_CBC, salt)
162 elif algo == "AES-192-CBC":
163 key = _EVP_BytesToKey(passphrase, salt[:8], 24)
164 objdec = AES.new(key, AES.MODE_CBC, salt)
165 elif algo == "AES-256-CBC":
166 key = _EVP_BytesToKey(passphrase, salt[:8], 32)
167 objdec = AES.new(key, AES.MODE_CBC, salt)
168 elif algo.lower() == "id-aes256-gcm":
169 key = _EVP_BytesToKey(passphrase, salt[:8], 32)
170 objdec = AES.new(key, AES.MODE_GCM, nonce=salt)
171 padding = False
172 else:
173 raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
174 lines = lines[2:]
175 else:
176 objdec = None
177
178 # Decode body
179 data = a2b_base64(''.join(lines[1:-1]))
180 enc_flag = False
181 if objdec:
182 if padding:
183 data = unpad(objdec.decrypt(data), objdec.block_size)
184 else:
185 # There is no tag, so we don't use decrypt_and_verify
186 data = objdec.decrypt(data)
187 enc_flag = True
188
189 return (data, marker, enc_flag)