|
| 1 | +from base64 import b64encode |
| 2 | + |
1 | 3 | import six |
2 | 4 |
|
3 | 5 | import Crypto.Hash.SHA256 |
4 | 6 | import Crypto.Hash.SHA384 |
5 | 7 | import Crypto.Hash.SHA512 |
6 | 8 |
|
7 | | -from Crypto.IO import PEM |
8 | 9 | from Crypto.PublicKey import RSA |
9 | 10 | from Crypto.Signature import PKCS1_v1_5 |
10 | 11 | from Crypto.Util.asn1 import DerSequence |
|
26 | 27 | _RSAKey = RSA._RSAobj |
27 | 28 |
|
28 | 29 |
|
| 30 | +def _der_to_pem(der_key, marker): |
| 31 | + """ |
| 32 | + Perform a simple DER to PEM conversion. |
| 33 | + """ |
| 34 | + pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')] |
| 35 | + |
| 36 | + # Limit base64 output lines to 64 characters by limiting input lines to 48 characters. |
| 37 | + for chunk_start in range(0, len(der_key), 48): |
| 38 | + pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48])) |
| 39 | + |
| 40 | + pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8')) |
| 41 | + |
| 42 | + return b'\n'.join(pem_key_chunks) |
| 43 | + |
| 44 | + |
29 | 45 | class RSAKey(Key): |
30 | 46 | """ |
31 | 47 | Performs signing and verification operations using |
@@ -159,7 +175,7 @@ def to_pem(self, pem_format='PKCS8'): |
159 | 175 | else: |
160 | 176 | pkcs8_der = self.prepared_key.exportKey('DER') |
161 | 177 | pkcs1_der = rsa_public_key_pkcs8_to_pkcs1(pkcs8_der) |
162 | | - pem = PEM.encode(pkcs1_der, 'RSA PUBLIC KEY').encode('utf-8') |
| 178 | + pem = _der_to_pem(pkcs1_der, 'RSA PUBLIC KEY') |
163 | 179 | return pem |
164 | 180 | else: |
165 | 181 | pem = self.prepared_key.exportKey('PEM', pkcs=pkcs) |
|
0 commit comments