~ubuntu-branches/ubuntu/maverick/pyca/maverick

« back to all changes in this revision

Viewing changes to pylib/certhelper.py

  • Committer: Bazaar Package Importer
  • Author(s): Lars Bahner
  • Date: 2003-12-02 19:39:35 UTC
  • Revision ID: james.westby@ubuntu.com-20031202193935-fzzt289mntvy6a8q
Tags: upstream-20031118
ImportĀ upstreamĀ versionĀ 20031118

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
########################################################################
 
2
# certhelper.py
 
3
# (c) by Michael Stroeder, michael@stroeder.com
 
4
########################################################################
 
5
# Deal with X.509 certificates and cert requests with
 
6
# plain Python 1.5.2 lib
 
7
########################################################################
 
8
 
 
9
import string, re, base64, md5, sha
 
10
 
 
11
pem_re = re.compile('-----BEGIN (CERTIFICATE|X509 CRL|CERTIFICATE REQUEST)-----([ \w+/=\r\n]+?)-----END (CERTIFICATE|X509 CRL|CERTIFICATE REQUEST)-----',re.S+re.M)
 
12
 
 
13
def MD5Fingerprint(cert_der='',delimiter=':'):
 
14
  """
 
15
  MD5 fingerprint in dotted notation (delimiter between bytes)
 
16
  """
 
17
  cert_md5 = md5.new(cert_der).digest()
 
18
  cert_fingerprint = []
 
19
  for i in cert_md5:
 
20
    cert_fingerprint.append(string.upper('%02x' % (ord(i))))
 
21
  return string.join(cert_fingerprint,delimiter)
 
22
 
 
23
def SHA1Fingerprint(cert_der='',delimiter=':'):
 
24
  """
 
25
  Return SHA-1 fingerprint in dotted notation (delimiter between bytes)
 
26
  """
 
27
  cert_sha1 = sha.new(cert_der).digest()
 
28
  cert_fingerprint = []
 
29
  for i in cert_sha1:
 
30
    cert_fingerprint.append(string.upper('%02x' % (ord(i))))
 
31
  return string.join(cert_fingerprint,delimiter)
 
32
 
 
33
def extract_pem(cert_text):
 
34
  """
 
35
  Extract all base64 encoded certs in a text file to a list of strings
 
36
  """
 
37
  result = []
 
38
  for begin_type,cert_base64,end_type in pem_re.findall(cert_text):
 
39
    if begin_type!=end_type:
 
40
      raise ValueError,"-----BEGIN %s----- and -----END %s----- does not match" % (begin_type,end_type)
 
41
    result.append((begin_type,string.strip(cert_base64)))
 
42
  return result
 
43
 
 
44
def der2pem(cert_der,cert_type='CERTIFICATE'):
 
45
  """
 
46
  Convert single binary DER-encoded certificate to base64 encoded format
 
47
  """
 
48
  return """-----BEGIN %s-----
 
49
%s-----END %s-----
 
50
""" % (cert_type,base64.encodestring(cert_der),cert_type)
 
51
 
 
52
def pem2der(cert_text):
 
53
  """
 
54
  Convert single base64 encoded certificate to binary DER-encoded format
 
55
  """
 
56
  cert_type,cert_base64  = extract_pem(cert_text)[0]
 
57
  return base64.decodestring(string.strip(cert_base64))
 
58