| 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 |
__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 |
|
| 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 |
|
| 84 |
data = objenc.encrypt(pad(data, objenc.block_size)) |
| 85 |
elif passphrase is not None: |
| 86 |
raise ValueError("Empty password") |
| 87 |
|
| 88 |
|
| 89 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 139 |
lines = pem_data.replace(" ", '').split() |
| 140 |
|
| 141 |
|
| 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 |
|
| 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 |
|
| 186 |
data = objdec.decrypt(data) |
| 187 |
enc_flag = True |
| 188 |
|
| 189 |
return (data, marker, enc_flag) |