import logging
try:
    import OpenSSL.crypto
    OPENSSL = True
except ImportError:
    OPENSSL = False

LOGGER = logging.getLogger(__name__)


class X509Certificate():
    def __init__(self):
        self._certificate = None

    @property
    def certificate(self):
        return self._certificate

    @certificate.setter
    def certificate(self, data):
        if not OPENSSL:
            return
        data = data.strip()
        if not b'-----BEGIN CERTIFICATE-----' in data:
            LOGGER.warning('Missing certificate prefix')
            data = b'-----BEGIN CERTIFICATE-----\n' + data
        if not b'-----END CERTIFICATE-----' in data:
            LOGGER.warning('Missing certificate suffix')
            data = data + b'\n-----END CERTIFICATE-----'
        self._certificate = OpenSSL.crypto.load_certificate(
            OpenSSL.crypto.FILETYPE_PEM, data.decode())

    def decode(self):
        if OPENSSL:
            out = bytearray()
            out.extend(OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_TEXT, self.certificate))
            out.extend(b'\n')
            out.extend(OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_PEM, self.certificate))
            return out

@@ -396,16 +396,173 @@
  return%0A
+        try:%0A            data = data.decode()%0A        except UnicodeDecodeError:%0A            LOGGER.error('Invalid certificate encoding')%0A            return%0A
         
@@ -592,25 +592,24 @@
      if not 
-b
 '-----BEGIN 
@@ -711,17 +711,16 @@
  data = 
-b
 '-----BE
@@ -765,17 +765,16 @@
  if not 
-b
 '-----EN
@@ -885,17 +885,16 @@
  data + 
-b
 '%5Cn-----
@@ -1021,25 +1021,16 @@
 EM, data
-.decode()
 )%0A%0A    d
@@ -1056,32 +1056,66 @@
       if OPENSSL
+ and self._certificate is not None
 :%0A            ou

Handle invalid certificates