]>
gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/pem.py
1 # -*- coding: utf-8 -*-
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 '''Functions that load and write PEM-encoded files.'''
21 def _markers(pem_marker
):
22 '''Returns the start and end PEM markers
24 >>> _markers('RSA PRIVATE KEY')
25 ('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----')
29 return ('-----BEGIN %s-----' % pem_marker
,
30 '-----END %s-----' % pem_marker
)
32 def load_pem(contents
, pem_marker
):
35 @param contents: the contents of the file to interpret
36 @param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
37 when your file has '-----BEGIN RSA PRIVATE KEY-----' and
38 '-----END RSA PRIVATE KEY-----' markers.
40 @return the base64-decoded content between the start and end markers.
42 @raise ValueError: when the content is invalid, for example when the start
43 marker cannot be found.
47 (pem_start
, pem_end
) = _markers(pem_marker
)
52 for line
in contents
.split('\n'):
62 raise ValueError('Seen start marker "%s" twice' % pem_start
)
67 # Skip stuff before first marker
72 if in_pem_part
and line
== pem_end
:
80 pem_lines
.append(line
)
82 # Do some sanity checks
84 raise ValueError('No PEM start marker "%s" found' % pem_start
)
87 raise ValueError('No PEM end marker "%s" found' % pem_end
)
89 # Base64-decode the contents
90 pem
= ''.join(pem_lines
)
91 return base64
.decodestring(pem
)
93 def save_pem(contents
, pem_marker
):
96 @param contents: the contents to encode in PEM format
97 @param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
98 when your file has '-----BEGIN RSA PRIVATE KEY-----' and
99 '-----END RSA PRIVATE KEY-----' markers.
101 @return the base64-encoded content between the start and end markers.
105 (pem_start
, pem_end
) = _markers(pem_marker
)
107 b64
= base64
.encodestring(contents
).replace('\n', '')
108 pem_lines
= [pem_start
]
110 for block_start
in range(0, len(b64
), 64):
111 block
= b64
[block_start
:block_start
+ 64]
112 pem_lines
.append(block
)
114 pem_lines
.append(pem_end
)
117 return '\n'.join(pem_lines
)