Esempio n. 1
0
        def _check_privatekey():
            if not os.path.exists(self.privatekey_path):
                return False

            try:
                with open(self.path, 'rb') as public_key_fh:
                    publickey_content = public_key_fh.read()
                if self.format == 'OpenSSH':
                    current_publickey = crypto_serialization.load_ssh_public_key(
                        publickey_content, backend=default_backend())
                    publickey_content = current_publickey.public_bytes(
                        crypto_serialization.Encoding.PEM,
                        crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
                current_publickey = crypto.dump_publickey(
                    crypto.FILETYPE_ASN1,
                    crypto.load_publickey(crypto.FILETYPE_PEM,
                                          publickey_content))
            except Exception as dummy:
                return False

            try:
                desired_publickey = crypto.dump_publickey(
                    crypto.FILETYPE_ASN1,
                    crypto_utils.load_privatekey(self.privatekey_path,
                                                 self.privatekey_passphrase))
            except crypto_utils.OpenSSLBadPassphraseError as exc:
                raise PublicKeyError(exc)

            return current_publickey == desired_publickey
Esempio n. 2
0
def check_ca():
    #检查文件夹
    for dir in (cert_dir, sub_certdir):
        if os.path.exists(dir):
            if not os.path.isdir(dir):
                os.remove(dir)
                os.mkdir(dir)
        else:
            os.mkdir(dir)
    #检查 CA 证书
    if not os.path.exists(ca_keyfile):
        if not OpenSSL:
            logging.critical('CAkey.pem is not exist and OpenSSL is disabled, ABORT!')
            sys.exit(-1)
        logging.error('CAkey.pem 不存在,清空 certs 文件夹。')
        any(os.remove(x) for x in glob.glob(os.path.join(sub_certdir, '*.crt')))
        if GC.LISTEN_CHECKSYSCA and sys.platform.startswith('win'):
            logging.warning('CAkey.pem 不存在,将从系统证书中删除无效的 CA 证书')
        else:
            logging.warning('删除功能未启用或未支持,请自行删除 [%s CA] 证书' % ca_vendor)
        dump_ca()
    global ca_privatekey, ca_subject, sub_publickey, ca_thumbprint
    with open(ca_keyfile, 'rb') as fp:
        content = fp.read()
    ca = crypto.load_certificate(crypto.FILETYPE_PEM, content)
    ca_privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, content)
    ca_subject = ca.get_subject()
    ca_thumbprint = ca.digest('sha1')
    ca_certerror = True
    if os.path.exists(ca_certfile):
        with open(ca_certfile, 'rb') as fp:
            if fp.read() in content:
                ca_certerror = False
    if ca_certerror:
        with open(ca_certfile, 'wb') as fp:
            fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca))
    #检查系统 CA 证书
    if GC.LISTEN_CHECKSYSCA and import_ca() != 0:
        logging.warning('install root certificate failed, Please run as administrator/root/sudo')
    #检查伪造网站密钥
    if os.path.exists(sub_keyfile):
        with open(sub_keyfile, 'rb') as fp:
            content = fp.read()
        sub_publickey = crypto.load_publickey(crypto.FILETYPE_PEM, content)
    else:
        dump_subkey()
    sub_publickey_str = crypto.dump_publickey(crypto.FILETYPE_PEM, sub_publickey)
    #检查伪造网站证书
    certfiles = glob.glob(os.path.join(sub_certdir, '*.crt'))
    if certfiles:
        filename = random.choice(certfiles)
        with open(filename, 'rb') as fp:
            content = fp.read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, content)
        if not verify_certificate(ca, cert) or (sub_publickey_str !=
                crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey())):
            logging.error('Certs mismatch, delete Certs.')
            any(os.remove(x) for x in certfiles)
def test_generator():
    certificate, fingerprint, private_key = generate_key_pair()

    x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                   base64.b64decode(certificate))
    pkcs8 = crypto.load_privatekey(crypto.FILETYPE_ASN1,
                                   base64.b64decode(private_key))
    assert len(fingerprint) == 40
    assert x509.digest("sha1").decode("utf-8").replace(
        ":", "").lower() == fingerprint
    assert crypto.dump_publickey(crypto.FILETYPE_PEM,
                                 x509.get_pubkey()) == crypto.dump_publickey(
                                     crypto.FILETYPE_PEM, pkcs8)
Esempio n. 4
0
 def test_generate_certificate(self):
     cert = generate_certificate("maas")
     self.assertIsInstance(cert.cert, crypto.X509)
     self.assertIsInstance(cert.key, crypto.PKey)
     self.assertEqual(cert.cert.get_subject().CN, "maas")
     self.assertEqual(
         crypto.dump_publickey(crypto.FILETYPE_PEM, cert.cert.get_pubkey()),
         crypto.dump_publickey(crypto.FILETYPE_PEM, cert.key),
     )
     self.assertEqual(cert.key.bits(), 4096)
     self.assertEqual(cert.key.type(), crypto.TYPE_RSA)
     self.assertGreaterEqual(
         datetime.utcnow() + timedelta(days=3650),
         cert.expiration(),
     )
Esempio n. 5
0
        def _check_privatekey():
            if not os.path.exists(self.privatekey_path):
                return False

            current_publickey = crypto.dump_publickey(
                crypto.FILETYPE_ASN1,
                crypto.load_publickey(crypto.FILETYPE_PEM, open(self.path, 'rb').read())
            )

            desired_publickey = crypto.dump_publickey(
                crypto.FILETYPE_ASN1,
                crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase)
            )

            return hashlib.md5(current_publickey).hexdigest() == hashlib.md5(desired_publickey).hexdigest()
    def get_pub_key_certificate(self, certificate):

        try:
            pub = certificate.get_pubkey()

            # DER FORMAT
            pub_key_der = crypto.dump_publickey(crypto.FILETYPE_ASN1, pub)

            # PEM FORMAT
            pub_key_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, pub)
            return pub_key_der, pub_key_pem

        except Exception as e:
            print(e)
            return False
Esempio n. 7
0
def get_installation_token():
    delete_old(installation_token_file, [api_token_file, private_key_file])
    token = read_file(installation_token_file)
    if token:
        return token.rstrip("\r\n")
    print("Requesting installation token...")
    public_key = get_public_key()
    pem = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key)
    method = "v1/installation"
    data = {"client_public_key": pem.decode("utf-8")}
    reply = post(method, data)
    installation_token = server_public = None
    for row in reply:
        if "Token" in row:
            installation_token = row["Token"]["token"]
        elif "ServerPublicKey" in row:
            server_public = row["ServerPublicKey"]["server_public_key"]
    if not installation_token:
        raise Exception("No token returned by installation")
    if not server_public:
        raise Exception("No server public key returned by installation")
    write_file(installation_token_file, installation_token)
    write_file(server_public_file, server_public)
    register_device()
    return installation_token
Esempio n. 8
0
def get_fingerprint(path, passphrase=None, content=None, backend='pyopenssl'):
    """Generate the fingerprint of the public key. """

    privatekey = load_privatekey(path,
                                 passphrase=passphrase,
                                 content=content,
                                 check_passphrase=False,
                                 backend=backend)

    if backend == 'pyopenssl':
        try:
            publickey = crypto.dump_publickey(crypto.FILETYPE_ASN1, privatekey)
        except AttributeError:
            # If PyOpenSSL < 16.0 crypto.dump_publickey() will fail.
            try:
                bio = crypto._new_mem_buf()
                rc = crypto._lib.i2d_PUBKEY_bio(bio, privatekey._pkey)
                if rc != 1:
                    crypto._raise_current_error()
                publickey = crypto._bio_to_string(bio)
            except AttributeError:
                # By doing this we prevent the code from raising an error
                # yet we return no value in the fingerprint hash.
                return None
    elif backend == 'cryptography':
        publickey = privatekey.public_key().public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo)

    return get_fingerprint_of_bytes(publickey)
Esempio n. 9
0
def strip_key(pem):
    """ Return only the b64 part of the ASCII armored PEM.
    """

    key = crypto.load_privatekey(crypto.FILETYPE_PEM, pem)
    public_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
    return public_pem.replace(b"\n", b"").split(b"-----")[2]
Esempio n. 10
0
def generate_keypair():
    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "DE"
    cert.get_subject().ST = "Mecklenburg Vorpommern"
    cert.get_subject().L = "Greifswald"
    cert.get_subject().O = "MCWeb Server"
    cert.get_subject().OU = "DSM-Server"
    cert.get_subject().CN = "MCWeb DSM Server"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    public_key = cert.get_pubkey()
    # public_key, private_key
    return crypto.dump_publickey(crypto.FILETYPE_ASN1,
                                 public_key), crypto.dump_privatekey(
                                     crypto.FILETYPE_ASN1, k)
Esempio n. 11
0
 def __init__(self, keylen=1024):
     self._pk=crypto.PKey()
     self._key=self._pk.generate_key(crypto.TYPE_RSA, keylen)
     self._prikey=crypto.dump_privatekey(crypto.FILETYPE_PEM,self._pk)
     self._pubkey=crypto.dump_publickey(crypto.FILETYPE_PEM,self._pk)
     self._KeyLen=self._pk.bits()//8
     return
Esempio n. 12
0
    def findOrCreateSystem(param, pubkey):
        pubkey = crypto.dump_publickey(crypto.FILETYPE_PEM, pubkey)

        # ensure cache directory exists
        if not os.path.exists(param.cacheDir):
            os.makedirs(param.cacheDir)

        # find system
        for oldUuid in os.listdir(param.cacheDir):
            with open(_ssh_pubkey_file(param, oldUuid), "rb") as f:
                if pubkey == f.read():
                    return oldUuid

        # create new system
        newUuid = uuid.uuid4().hex
        dirname = os.path.join(param.cacheDir, newUuid)
        os.makedirs(dirname)

        # record public key
        with open(_ssh_pubkey_file(param, newUuid), "wb") as f:
            f.write(pubkey)

        # generate disk image
        fn = _image_file(param, newUuid)
#        GbsUtil.shell("/bin/dd if=/dev/zero of=%s bs=%d count=%s conv=sparse" % (fn, _gb(), param.imageSizeStep), "stdout")
        GbsUtil.shell("/bin/dd if=/dev/zero of=%s bs=%d count=%s conv=sparse" % (fn, _gb(), 40), "stdout")                              # fixme, on-line enlarg don't work
        GbsUtil.shell("/sbin/mkfs.ext4 -O ^has_journal %s" % (fn), "stdout")

        return newUuid
Esempio n. 13
0
def generate_rsa_keys_if_needed():
    """Generate RSA keys for MAAS.

    Returns True if a new RSA key was generated.
    """
    if os.path.isfile(MAAS_PRIVATE_KEY):
        return False
    try:
        with NamedLock("RSA"):
            os.makedirs(os.path.dirname(MAAS_PRIVATE_KEY), exist_ok=True)
            pkey = crypto.PKey()
            pkey.generate_key(crypto.TYPE_RSA, 4096)
            with open(MAAS_PRIVATE_KEY, "wb") as f:
                f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
            os.chmod(MAAS_PRIVATE_KEY, 0o600)
            with open(MAAS_PUBLIC_KEY, "wb") as f:
                f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, pkey))
    except NamedLock.NotAvailable:
        # System is running a region and rack. The other process
        # is generating the key, wait up to 60s for it.
        waits = 0
        while not os.path.isfile(MAAS_PRIVATE_KEY) and waits < 600:
            sleep(0.1)
            waits += 1
        assert os.path.isfile(
            MAAS_PRIVATE_KEY), "Unable to generate MAAS RSA keys!"
    return True
Esempio n. 14
0
 def _get_public_key(self, binary):
     try:
         return crypto.dump_publickey(
             crypto.FILETYPE_ASN1 if binary else crypto.FILETYPE_PEM,
             self.cert.get_pubkey())
     except AttributeError:
         try:
             # pyOpenSSL < 16.0:
             bio = crypto._new_mem_buf()
             if binary:
                 rc = crypto._lib.i2d_PUBKEY_bio(
                     bio,
                     self.cert.get_pubkey()._pkey)
             else:
                 rc = crypto._lib.PEM_write_bio_PUBKEY(
                     bio,
                     self.cert.get_pubkey()._pkey)
             if rc != 1:
                 crypto._raise_current_error()
             return crypto._bio_to_string(bio)
         except AttributeError:
             self.module.warn(
                 'Your pyOpenSSL version does not support dumping public keys. '
                 'Please upgrade to version 16.0 or newer, or use the cryptography backend.'
             )
Esempio n. 15
0
def cert_to_jwk(certificates: str, public_key: str) -> str:
    """
    coverts a pem public key and a pem certificate chain to a jwk with a x5c element
    :param certificates: the certificates for the x5c as pem key list
    :param public_key: the pem public key as string
    :return: the jwk as string
    """

    # convert public key to jwk
    public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key)
    jwk = JWK.load(crypto.dump_publickey(crypto.FILETYPE_PEM, public_key))

    # covert cert chain to base64 encoded ASN1 according to https://tools.ietf.org/html/rfc7517#section-4.7
    x5c = []
    for cert in pem.parse(str.encode(certificates)):
        cert_pem = crypto.load_certificate(crypto.FILETYPE_PEM,
                                           cert.as_bytes())
        x5c.append(
            base64.b64encode(
                crypto.dump_certificate(crypto.FILETYPE_ASN1,
                                        cert_pem)).decode())

    # dump jwk obj to json and add x5c cer chain
    jwk_j = jwk.to_json()
    jwk_j["x5c"] = x5c
    return json.dumps(jwk_j)
def create_group_cert(cli):
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)  # generate RSA key-pair

    cert = crypto.X509()
    cert.get_subject().countryName = "US"
    cert.get_subject().stateOrProvinceName = "CA"
    cert.get_subject().organizationName = "mini-fulfillment"
    cert.get_subject().organizationalUnitName = "demo"
    cert.get_subject().commonName = "mini-fulfillment"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60)  # 5 year expiry date
    cert.set_issuer(cert.get_subject())  # self-sign this certificate
    cert.set_pubkey(k)
    san_list = ["IP:{0}".format(cli.ip_address)]
    extension_list = [
        crypto.X509Extension(type_name=b"basicConstraints",
                             critical=False, value=b"CA:false"),
        crypto.X509Extension(type_name=b"subjectAltName",
                             critical=True, value=", ".join(san_list)),
        # crypto.X509Extension(type_name=b"subjectKeyIdentifier",
        #                      critical=True, value=b"hash")
    ]
    cert.add_extensions(extension_list)
    cert.sign(k, 'sha256')

    prefix = str(cli.out_dir) + '/' + cli.group_name

    open("{0}-server.crt".format(prefix), 'wt').write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open("{0}-server-private.key".format(prefix), 'wt').write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey=k))
    open("{0}-server-public.key".format(prefix), 'wt').write(
        crypto.dump_publickey(crypto.FILETYPE_PEM, pkey=k))
Esempio n. 17
0
def generate_keys():
    if request.method == "POST":
        # Sets the size of the RSA Key
        size = request.form.get("size", type=int)
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, size)

        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
        # Auto selects the private key filename accordingly to not overwrite
        existing_files = fnmatch.filter((f for f in os.listdir(path_to_keys)),
                                        "private_*.pem")
        path_pvt = path_to_keys + "/private_key_%d.pem" % (
            len(existing_files) + 1)
        file_out = open(path_pvt, "wb")
        file_out.write(private_key)
        file_out.close()

        # Auto selects the public key filename accordingly to not overwrite
        public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
        existing_files = fnmatch.filter((f for f in os.listdir(path_to_keys)),
                                        "public_*.pem")
        path_pub = path_to_keys + "/public_key_%d.pem" % (len(existing_files) +
                                                          1)
        file_out = open(path_pub, "wb")
        file_out.write(public_key)
        file_out.close()

        return render_template("keys_generated.html",
                               path_pub=path_pub,
                               path_pvt=path_pvt)
    else:
        return render_template("generate_keys.html")
Esempio n. 18
0
        def _check_privatekey():
            if not os.path.exists(self.privatekey_path):
                return False

            current_publickey = crypto.dump_publickey(
                crypto.FILETYPE_ASN1,
                crypto.load_publickey(crypto.FILETYPE_PEM,
                                      open(self.path, 'rb').read()))

            desired_publickey = crypto.dump_publickey(
                crypto.FILETYPE_ASN1,
                crypto_utils.load_privatekey(self.privatekey_path,
                                             self.privatekey_passphrase))

            return hashlib.md5(current_publickey).hexdigest() == hashlib.md5(
                desired_publickey).hexdigest()
Esempio n. 19
0
def create_self_signed_cert(name, surname):
    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "PL"
    cert.get_subject().ST = "Poznan"
    cert.get_subject().L = "Poznan"
    cert.get_subject().O = str(name)+" "+str(surname)
    cert.get_subject().OU = "Politechnika Poznanska"
    cert.get_subject().CN = str(name).lower()+".pki.put.poznan.pl"
    #cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(31556952)  # in seconds = 1 year
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    certificate = crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8')
    private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode('utf-8')
    public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, k).decode('utf-8')
    not_before = cert.get_notBefore()
    not_after = cert.get_notAfter()
    return certificate, private_key, public_key, not_before, not_after
def generate_key(
    prefix: str,
    path: typing.Union[str, Path],
    type: str = crypto.TYPE_RSA,
    bits: int = 4096,
):
    if not isinstance(path, Path):
        path = Path(path).resolve().expanduser()

    assert (path.exists()
            and path.is_dir()), f'invalid key storage path {path!s}'

    pubfile = path / f'{prefix}.pub'
    keyfile = path / f'{prefix}.key'

    if pubfile.exists():
        raise FileExistsError(f'{pubfile!s}')
    if keyfile.exists():
        raise FileExistsError(f'{keyfile!s}')

    key = crypto.PKey()
    key.generate_key(type, bits)
    with open(keyfile, 'wb') as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
    with open(pubfile, 'wb') as f:
        f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, key))
Esempio n. 21
0
 def enc_prekey(self):
     crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, self.C_Certs[0])
     pubKeyObject = crtObj.get_pubkey()
     pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
     key = RSA.importKey(pubKeyString)
     Encrypter = PKCS1OAEP_Cipher(key, None, None, None)
     return Encrypter.encrypt(self.PKs)
Esempio n. 22
0
def rsa_cert_to_key(path):
    with open(path) as f:
        cert = f.read()
    crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    pubKeyObject = crtObj.get_pubkey()
    pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
    return pubKeyString
Esempio n. 23
0
    def generate(self, module):
        """Generate the public key.."""

        if not os.path.exists(self.path) or self.force:
            try:
                privatekey_content = open(self.privatekey_path, 'r').read()
                privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                                    privatekey_content)
                publickey_file = open(self.path, 'w')
                publickey_file.write(
                    crypto.dump_publickey(crypto.FILETYPE_PEM, privatekey))
                publickey_file.close()
            except (IOError, OSError):
                e = get_exception()
                raise PublicKeyError(e)
            except AttributeError:
                self.remove()
                raise PublicKeyError(
                    'You need to have PyOpenSSL>=16.0.0 to generate public keys'
                )
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
Esempio n. 24
0
    def __init__(self, *args, **kwargs):

        signature = kwargs.get('signature')

        public_key = kwargs.get('public_key')
        private_key = kwargs.get('private_key')

        if not signature:
            raise Exception('Missing signature argument')

        if not public_key:
            raise Exception('Missing public_key argument')

        if not private_key:
            raise Exception('Missing private_key argument')

        # read public key
        # parse the public key and save it as a string
        with open(public_key, "r") as file:
            pub_key = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              file.read()).get_pubkey()
            public_key_string = crypto.dump_publickey(crypto.FILETYPE_PEM,
                                                      pub_key)

        # read private key
        with open(private_key, "r") as file:
            private_key_string = file.read()

        self.signature = signature
        self.public_key = public_key_string
        self.private_key = private_key_string

        # a flag to keep track if we are in developement mode
        # if True => more logging
        self.developement = kwargs.get('developement', False)
Esempio n. 25
0
 def get_public_key(self):
     """
         Get Raw PEM Signatura Public Key from Citizen Card Certificate
     """
     cert = self.get_certificate()
     public_key_string = crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey())
     return public_key_string
Esempio n. 26
0
def part6():
    print("6th part:")
    file_subject = open(sys.argv[3], 'rt')
    cert_subject = crypto.load_certificate(crypto.FILETYPE_PEM,file_subject.read())
    key_encoded = crypto.dump_publickey(crypto.FILETYPE_PEM,cert_subject.get_pubkey())
    pubkey2 = serialization.load_pem_public_key(
        key_encoded,
        backend=default_backend())
    message = b"Hello world"
    ciphertext = pubkey2.encrypt(
        message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    p12 = crypto.load_pkcs12(open(sys.argv[1], 'rb').read(), sys.argv[4].encode())

    key_encoded = crypto.dump_privatekey(crypto.FILETYPE_PEM,p12.get_privatekey(),None,sys.argv[4].encode())
    prikey2 = serialization.load_pem_private_key(
    key_encoded,password=None,
    backend=default_backend())
    plaintext = prikey2.decrypt(
        ciphertext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    print("Ciphertext: %s" %ciphertext.hex())
    print("Plaintext: %s" %plaintext)
    print("\n\n")
Esempio n. 27
0
def get_installation_token():
    token = os.getenv('BUNQ_INSTALLATION_TOKEN')
    if token:
        return token.rstrip("\r\n")

    print("Requesting installation token...")
    public_key = get_public_key()
    pem = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key)
    method = "v1/installation"
    data = {"client_public_key": pem.decode("utf-8")}
    reply = post(method, data)
    installation_token = server_public = None

    for row in reply:
        if "Token" in row:
            installation_token = row["Token"]["token"]
        elif "ServerPublicKey" in row:
            server_public = base64.b64encode(
                row["ServerPublicKey"]["server_public_key"].encode('utf-8'))

    if not installation_token:
        raise Exception("No token returned by installation")
    else:
        print("Set BUNQ_INSTALLATION_TOKEN to '%s'." % installation_token)

    if not server_public:
        raise Exception("No server public key returned by installation")
    else:
        print("Set BUNQ_SERVER_PUBLIC_KEY to '%s'." %
              str(server_public.decode('utf-8')))

    os.environ['BUNQ_INSTALLATION_TOKEN'] = installation_token
    os.environ['BUNQ_SERVER_PUBLIC_KEY'] = str(server_public.decode('utf-8'))
    register_device()
    return installation_token
Esempio n. 28
0
    def _get_instance_ssl_context(self):
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)

        public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

        request = self._api_client().sslCerts().createEphemeral(
            project=self._project,
            instance=self._instance,
            body={'public_key': public_key})

        ephemeral = request.execute()

        client_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              ephemeral['cert'])
        ca_cert = crypto.load_certificate(
            crypto.FILETYPE_PEM, self._metadata['serverCaCert']['cert'])

        context = SSL.Context(SSL.TLSv1_2_METHOD)
        context.set_verify(SSL.VERIFY_PEER, self._verify_cert)
        context.use_privatekey(key)
        context.use_certificate(client_cert)
        context.get_cert_store().add_cert(ca_cert)

        return context
Esempio n. 29
0
def generate_offline_keyandcsr(id,
                               password,
                               outputdir,
                               digest="sha256",
                               **name):
    """
    Generates a private key and csr and outputs to file.
    Arguments: id - unique identifier to identify key and csr. These will be out to files based on the id
               digest - The hashing algo to use to create the csr
               **name - The name of the subject of the request, possible
                        arguments are:
                          C     - Country name
                          ST    - State or province name
                          L     - Locality name
                          O     - Organization name
                          OU    - Organizational unit name
                          CN    - Common name
                          emailAddress - E-mail address
                          eg = CN='FA10234587B',OU='OEM 5G ICL',O='Verizon', C='US',
    Returns:   True or False
    :type password: object
    """
    logger.info('Start key/csr generation for id %s', id)
    pkey = create_key_pair(keytype, keysize, keygen, id)
    publickey = crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, pkey)
    privatekey = crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey)
    logger.info('SHA256 hash of Public Key Object for id:%s is %s', id,
                hashlib.sha256(publickey).hexdigest())
    logger.info('SHA256 hash of Private Key Object for id:%s is %s', id,
                hashlib.sha256(privatekey).hexdigest())
    # 1. Generate key pair using create_key_pair and output to temp file - id.pkey
    '''keyfile = os.path.join(batchdir, id + '.pkey')
    if os.path.exists(keyfile):
        # Identified duplicate key identifier - needs further investigation.
        logger.error('Private Key file for %s exists at %s aborting', id, keyfile)
        sys.exit(1)
    else:
        pkey = create_key_pair(keytype, keysize, keygen, id)
        open(keyfile, "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey, str(keycipher), b'password'))
        logger.info('Private Key generated for %s and written to %s', id, keyfile)'''

    # 2. Generate CSR output to temp file - id.csr
    csrfile = os.path.join(outputdir, id + '.csr')

    if os.path.exists(csrfile):
        logger.error('CSR file for %s exists at %s aborting', id, csrfile)
        sys.exit(1)
    else:
        csr = create_cert_request(pkey, digest="sha256", **name)
        f = open(csrfile, "wb")
        f.write(
            OpenSSL.crypto.dump_certificate_request(
                OpenSSL.crypto.FILETYPE_PEM, csr))
        f.close()
        logger.info('CSR file created for %s and written to %s', id, csrfile)

    # 3. Generate P12 and output to file id.p12

    create_pkcs12(id, pkey, cacert, outputdir, password)
Esempio n. 30
0
 def get_subject(self):
     crt_obj = crypto.load_certificate(
         crypto.FILETYPE_PEM,
         open("temp/certificate.crt", 'rb').read())
     pub_key_object = crt_obj.get_pubkey()
     pub_key_string = crypto.dump_publickey(crypto.FILETYPE_PEM,
                                            pub_key_object)
     return (crt_obj.get_subject().CN, crt_obj.get_issuer().CN)
Esempio n. 31
0
def extract_public_key_from_crt(cert_path=cert_path):
    ## get public key with openssl
    ## openssl x509 -pubkey -noout -in ChaveCifraPublicaAT2020.cer >public_key.pem
    f = open(cert_path, 'rt')
    crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
    pubKeyObject = crtObj.get_pubkey()
    pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
    return pubKeyString
Esempio n. 32
0
    def hpkp_pin(self):
        # taken from
        # https://github.com/shazow/urllib3/pull/607/files#diff-f86c7f2eb1a0a2deadac493decdd0b7eR337

        key = self.x509.get_pubkey()
        public_key_raw = crypto.dump_publickey(crypto.FILETYPE_ASN1, key)
        public_key_hash = hashlib.sha256(public_key_raw).digest()
        return base64.b64encode(public_key_hash).decode('utf-8')
Esempio n. 33
0
 def __init__(self,  bits):
     self.check = True
     pkey = crypto.PKey()
     pkey.generate_key(crypto.TYPE_RSA, bits)
     open('PrivateKey.pem', 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM,pkey))
     open('PublicKey.pem', 'w').write(crypto.dump_publickey(crypto.FILETYPE_PEM, pkey))
     self.priKey = RSA.importKey(open('PublicKey.pem').read())
     self.pubKey = RSA.importKey(open('PrivateKey.pem').read())
Esempio n. 34
0
def dump_subkey():
    global sub_publickey
    sub_key = crypto.PKey()
    sub_key.generate_key(crypto.TYPE_RSA, 2048)
    with open(sub_keyfile, 'wb') as fp:
        fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, sub_key))
        fp.write(crypto.dump_publickey(crypto.FILETYPE_PEM, sub_key))
    sub_publickey = sub_key
Esempio n. 35
0
 def get_pub_key(self):
     crt_obj = crypto.load_certificate(
         crypto.FILETYPE_PEM,
         open("cert/certificate.crt", 'rb').read())
     pub_key_object = crt_obj.get_pubkey()
     pub_key_string = crypto.dump_publickey(crypto.FILETYPE_PEM,
                                            pub_key_object)
     return pub_key_string
def fingerprint(cert):
    if isinstance(cert, X509):
        return cert.digest("sha1").decode()
    elif isinstance(cert, X509Req):
        req = cert
        pub_key = req.get_pubkey()
        data = "".join(crypto.dump_publickey(crypto.FILETYPE_PEM, pub_key).split("\n")[1:-2])
        digest = hashlib.sha1(data).hexdigest()

        return ':'.join(a+b for a,b in zip(digest[::2], digest[1::2]))
 def generate_rsa_key_pair(self, bits):
     key = crypto.PKey()
     key.generate_key(crypto.TYPE_RSA, bits)
     public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, key).decode()
     private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode()
     public_key = public_key.replace("-----BEGIN PUBLIC KEY-----", "")
     public_key = public_key.replace("-----END PUBLIC KEY-----", "")
     public_key = public_key.replace("\n", "")
     private_key = private_key.replace("-----BEGIN PRIVATE KEY-----", "")
     private_key = private_key.replace("-----END PRIVATE KEY-----", "")
     private_key = private_key.replace("\n", "")
     return public_key, private_key
Esempio n. 38
0
def createDGPairs(username):
    private_path = 'private/'
    public_path = 'public/'
    private_path += username
    public_path += username
    P = PKey()
    P.generate_key(TYPE_RSA, 1024)
    #写入
    with open(public_path,'w') as f:
        f.write(dump_publickey(FILETYPE_PEM, P).decode('utf-8'))
    with open(private_path,'w') as f:
        f.write(dump_privatekey(FILETYPE_PEM, P).decode('utf-8'))
Esempio n. 39
0
File: init.py Progetto: regnarg/bc
def main(dir, *, synctree=False, name:'n'=None):
    if dir: os.chdir(dir or '.')
    try: store, sub = Store.find()
    except StoreNotFound: pass
    else: err('Directory %s already in a Filoco store (%s).' % (os.getcwd(), store.root_path))
    try:
        if os.path.exists('.filoco.tmp'): shutil.rmtree('.filoco.tmp')
        os.mkdir('.filoco.tmp')
        spurt('.filoco.tmp/version', "1")
        spurt('.filoco.tmp/type', "fs")
        db = SqliteWrapper('.filoco.tmp/meta.sqlite', wal=True)
        sync_mode = 'synctree' if synctree else 'serial'
        spurt('.filoco.tmp/sync_mode', sync_mode)
        tpl = jinja2.Template(slurp(SCHEMA_FILE), line_statement_prefix='#')
        schema = tpl.render(sync_mode=sync_mode)
        db.execute(schema)

        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, RSA_KEY_SIZE)
        priv_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
        pub_key = crypto.dump_publickey(crypto.FILETYPE_PEM, key)

        cert = crypto.X509()
        cert.get_subject().CN = name or 'unnamed'
        cert.set_serial_number(1000)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(10*365*24*60*60)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key)
        cert.sign(key, 'sha256')

        store_id = cert.digest('sha256').decode('ascii').replace(':','').lower()
        spurt('.filoco.tmp/store_id', store_id)

        db.insert('stores', idx=0, id=store_id)

        spurt('.filoco.tmp/store_cert', crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('ascii'))
        with open('.filoco.tmp/store_key', 'wb') as file:
            os.chmod('.filoco.tmp/store_key', 0o600)
            file.write(priv_key)

        st = os.lstat('.')
        handle = butter.fhandle.name_to_handle_at(butter.fhandle.AT_FDCWD, '.')[0]
        db.insert('inodes', iid='ROOT', ino=st.st_ino, handle_type=handle.type, handle=handle.handle,
                size=st.st_size, mtime=st.st_mtime, type='d')

        os.rename('.filoco.tmp', '.filoco')
        
    except:
        try: shutil.rmtree('.filoco.tmp')
        except OSError: pass
        raise
Esempio n. 40
0
        def _check_privatekey():
            if not os.path.exists(self.privatekey_path):
                return False

            try:
                publickey_content = open(self.path, 'rb').read()
                if self.format == 'OpenSSH':
                    current_publickey = crypto_serialization.load_ssh_public_key(publickey_content, backend=default_backend())
                    publickey_content = current_publickey.public_bytes(crypto_serialization.Encoding.PEM,
                                                                       crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
                current_publickey = crypto.dump_publickey(
                    crypto.FILETYPE_ASN1,
                    crypto.load_publickey(crypto.FILETYPE_PEM, publickey_content)
                )
            except (crypto.Error, ValueError):
                return False

            desired_publickey = crypto.dump_publickey(
                crypto.FILETYPE_ASN1,
                crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase)
            )

            return current_publickey == desired_publickey
Esempio n. 41
0
def get_fingerprint(path, passphrase=None):
    """Generate the fingerprint of the public key. """

    fingerprint = {}

    privatekey = load_privatekey(path, passphrase)
    try:
        publickey = crypto.dump_publickey(crypto.FILETYPE_ASN1, privatekey)
        for algo in hashlib.algorithms:
            f = getattr(hashlib, algo)
            pubkey_digest = f(publickey).hexdigest()
            fingerprint[algo] = ':'.join(pubkey_digest[i:i + 2] for i in range(0, len(pubkey_digest), 2))
    except AttributeError:
        # If PyOpenSSL < 16.0 crypto.dump_publickey() will fail.
        # By doing this we prevent the code from raising an error
        # yet we return no value in the fingerprint hash.
        pass

    return fingerprint
Esempio n. 42
0
    def generate(self, module):
        """Generate the public key."""

        if not os.path.exists(self.privatekey_path):
            raise PublicKeyError(
                'The private key %s does not exist' % self.privatekey_path
            )

        if not self.check(module, perms_required=False) or self.force:
            try:
                if self.format == 'OpenSSH':
                    privatekey_content = open(self.privatekey_path, 'rb').read()
                    key = crypto_serialization.load_pem_private_key(privatekey_content,
                                                                    password=self.privatekey_passphrase,
                                                                    backend=default_backend())
                    publickey_content = key.public_key().public_bytes(
                        crypto_serialization.Encoding.OpenSSH,
                        crypto_serialization.PublicFormat.OpenSSH
                    )
                else:
                    self.privatekey = crypto_utils.load_privatekey(
                        self.privatekey_path, self.privatekey_passphrase
                    )
                    publickey_content = crypto.dump_publickey(crypto.FILETYPE_PEM, self.privatekey)

                with open(self.path, 'wb') as publickey_file:
                    publickey_file.write(publickey_content)

                self.changed = True
            except (IOError, OSError) as exc:
                raise PublicKeyError(exc)
            except AttributeError as exc:
                self.remove()
                raise PublicKeyError('You need to have PyOpenSSL>=16.0.0 to generate public keys')

        self.fingerprint = crypto_utils.get_fingerprint(
            self.privatekey_path,
            self.privatekey_passphrase
        )
        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
Esempio n. 43
0
    def generate(self, module):
        """Generate the public key.."""

        if not os.path.exists(self.path) or self.force:
            try:
                 privatekey_content = open(self.privatekey_path, 'r').read()
                 privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)
                 publickey_file = open(self.path, 'w')
                 publickey_file.write(crypto.dump_publickey(crypto.FILETYPE_PEM, privatekey))
                 publickey_file.close()
            except (IOError, OSError):
                e = get_exception()
                raise PublicKeyError(e)
            except AttributeError:
                self.remove()
                raise PublicKeyError('You need to have PyOpenSSL>=16.0.0 to generate public keys')
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
Esempio n. 44
0
File: dkim.py Progetto: insxa/Mailu
def strip_key(pem):
    """ Return only the b64 part of the ASCII armored PEM.
    """
    key = crypto.load_privatekey(crypto.FILETYPE_PEM, pem)
    public_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
    return public_pem.replace(b"\n", b"").split(b"-----")[2]
Esempio n. 45
0
def main():
    """ Main function"""
    parser = argparse.ArgumentParser(description='csr2dnskey')
    parser.add_argument("--csr",
                        dest='csr',
                        metavar='filename',
                        help='CSR anchor file (root-anchors.xml)',
                        required=True)
    parser.add_argument("--output",
                        dest='output',
                        metavar='filename',
                        help='output file (stdout)')
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true',
                        help="Enable debugging")
    group_dnskey = parser.add_mutually_exclusive_group()
    group_dnskey.add_argument('--dnskey',
                              dest='output_dnskey',
                              action='store_true',
                              default=True,
                              help="Output DNSKEY RR")
    group_dnskey.add_argument('--no-dnskey',
                              dest='output_dnskey',
                              action='store_false',
                              help="Don't output DNSKEY RR")
    group_ds = parser.add_mutually_exclusive_group()
    group_ds.add_argument('--ds',
                          dest='output_ds',
                          action='store_true',
                          default=False,
                          help="Output DS RR")
    group_ds.add_argument('--no-ds',
                          dest='output_ds',
                          action='store_false',
                          help="Don't output DS RR")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    with open(args.csr, "rb") as csr_fd:
        csr = csr_fd.read()

    req = load_certificate_request(FILETYPE_ASN1, csr)
    subject = req.get_subject()
    logging.info("CSR Subject: %s", subject)
    (ds_origin, ds_rdata) = get_ds_rdata(subject)
    logging.debug("CSR DS Origin: %s", ds_origin)
    logging.debug("CSR DS RDATA: %s", ds_rdata)
    public_key_der = dump_publickey(FILETYPE_ASN1, req.get_pubkey())
    debug_hexlify("CSR Public Key", public_key_der)

    if get_algo_class_from_ds(ds_rdata) == 'RSA':
        b64 = get_rsa_b64_from_der(public_key_der).decode()
        logging.debug("CSR Public RSA Key (Base64): %s", b64)
        rdata_str = '257 3 {} {}'.format(ds_rdata.algorithm, b64)
        dnskey_rdata = dns.rdata.from_text(rdclass=dns.rdataclass.IN,
                                           rdtype=dns.rdatatype.DNSKEY,
                                           tok=rdata_str)
        logging.debug("DNSKEY RDATA: %s", dnskey_rdata)
        dnskey_as_ds = dns.dnssec.make_ds(name=ds_origin,
                                          key=dnskey_rdata,
                                          algorithm=ds_digest_type_as_text(ds_rdata.digest_type))
        logging.debug("DNSKEY as DS RDATA: %s", dnskey_as_ds)
    else:
        raise Exception('Unsupported public key algorithm')

    if ds_rdata != dnskey_as_ds:
        raise Exception('DNSKEY/DS mismatch')

    if args.output:
        output_fd = open(args.output, 'w')
        old_stdout = sys.stdout
        sys.stdout = output_fd

    if args.output_ds:
        print('{} IN DS {}'.format(ds_origin, ds_rdata))

    if args.output_dnskey:
        print('{} IN DNSKEY {}'.format(ds_origin, dnskey_rdata))

    if args.output:
        sys.stdout = old_stdout
        output_fd.close()
Esempio n. 46
0
 def verifySignature(self, signature, signersCert, data):
     'Will verify the signature of an entity based upon public cert'
     vk = ecdsa.VerifyingKey.from_der(crypto.dump_publickey(crypto.FILETYPE_ASN1, signersCert.get_pubkey()))
     assert vk.verify(signature, data, hashfunc=self.hashfunc, sigdecode=self.sigdecode), "Invalid signature!!"
Esempio n. 47
0
import M2Crypto

#following data are in 9th packet
#subjectPublicKeyInfo of the 2nd certificate which is used to sign the 1st
key = '30820122300d06092a864886f70d01010105000382010f003082010a0282010100b2d805ca1c742db5175639c54a520996e84bd80cf1689f9a422862c3a530537e5511825b037a0d2fe17904c9b496771981019459f9bcf77a9927822db783dd5a277fb2037a9c5325e9481f464fc89d29f8be7956f6f7fdd93a68da8b4b82334112c3c83cccd6967a84211a22040327178b1c6861930f0e5180331db4b5ceeb7ed062aceeb37b0174ef6935ebcad53da9ee9798ca8daa440e25994a1596a4ce6d02541f2a6a26e2063a6348acb44cd1759350ff132fd6dae1c618f59fc9255df3003ade264db42909cd0f3d236f164a8116fbf28310c3b8d6d855323df1bd0fbd8c52954a16977a522163752f16f9c466bef5b509d8ff2700cd447c6f4b3fb0f70203010001'.decode('hex')
#encrypted hash of the 1st certificate
encHash = '01b9a2f6b47996333035fa09a9fbf7a9937afe51ce0f95a3fb9f80037e1d63a6d0f7044b7198e2f07e104768545b4a5d43c19240ec911a7f90208d6886df74db949bb615e8e10118d41333c119e61e00702ad00ada8758bf70bd641fed22ee59816f8f2a1ddc728d5c37c03faaa6b225ee8ff0872242dfb2f1dccb7e4c66b63f24cf117bfe2ab1edd111aa959ae0d198bfa52723782e22484e065b6ed1b0870af9f6ab31df75cc6e75f3196a951aedf3d8dee807e9eb7ff61f0cfef5cf39729bb8e3fab966b95ef4c0dfb3f327dc327e07ab3b4c3bdb1b91787302cc4272890086dc9b5cef0acc4886a84ccd073e768b38d4c80f51e2da12c343f2893f9a84f3'.decode('hex')
#content of 1st certificate
cert = '308207b8a00302010202105f4572da7b32a3d03c7666978b37fc25300d06092a864886f70d01010b0500307e310b3009060355040613025553311d301b060355040a131453796d616e74656320436f72706f726174696f6e311f301d060355040b131653796d616e746563205472757374204e6574776f726b312f302d0603550403132653796d616e74656320436c61737320332053656375726520536572766572204341202d204734301e170d3135303932333030303030305a170d3137303932333233353935395a307d310b30090603550406130255533113301106035504080c0a43616c69666f726e69613111300f06035504070c0853616e204a6f736531133011060355040a0c0a654261792c20496e632e31183016060355040b0c0f53697465204f7065726174696f6e733117301506035504030c0e70616765732e656261792e636f6d30820122300d06092a864886f70d01010105000382010f003082010a0282010100b21aea816c8a5a2e2203eeba246e1656c89fa7fdbcf4cfe293db92713292b93526118c48da91297574fd7942674a0c1e9b5e1b80450590a446a9baca472f9c0abe468afaa863f74330472f75a7024046da171248769d4989173ccd7e7bfca6028054655cf31110fc69db59ee97b1390142f7cdd9a12f5edd605552c5dc2371ea9a6d6ed7ab2677147404cf7754d541ddf5298b184c9d495b955927b6989b2d798be29cc936b50412d9fe7f0e25b9890d53d76051c012eb7a1d8b1ace7abce23420fbca5bdba4130af0454af4fbc2d660562fd4e658115900b727f38cfdb96702a3a121c0ba8a707644ab91e53f08568f86b6cd54ead564d993e47b388f15d0e50203010001a3820549308205453082027b0603551d11048202723082026e820c626566722e656261792e6265820c62656e6c2e656261792e6265820c636166722e656261792e63618207656261792e61748207656261792e62658207656261792e63618207656261792e6368820a656261792e636f2e756b8208656261792e636f6d820b656261792e636f6d2e6175820b656261792e636f6d2e686b820b656261792e636f6d2e6d79820b656261792e636f6d2e73678207656261792e64658207656261792e65738207656261792e66728207656261792e69658207656261792e696e8207656261792e69748207656261792e6e6c8207656261792e70688207656261792e706c8207656261792e7275821270616765732e626566722e656261792e6265821270616765732e62656e6c2e656261792e6265821270616765732e636166722e656261792e6361820d70616765732e656261792e6174820d70616765732e656261792e6265820d70616765732e656261792e6361820d70616765732e656261792e6368821070616765732e656261792e636f2e756b820e70616765732e656261792e636f6d821170616765732e656261792e636f6d2e6175821170616765732e656261792e636f6d2e686b821170616765732e656261792e636f6d2e6d79821170616765732e656261792e636f6d2e7367820d70616765732e656261792e6465820d70616765732e656261792e6573820d70616765732e656261792e6672820d70616765732e656261792e6965820d70616765732e656261792e696e820d70616765732e656261792e6974820d70616765732e656261792e6e6c820d70616765732e656261792e7068820d70616765732e656261792e706c820d70616765732e656261792e727530090603551d1304023000300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b0601050507030230610603551d20045a30583056060667810c010202304c302306082b06010505070201161768747470733a2f2f642e73796d63622e636f6d2f637073302506082b0601050507020230191a1768747470733a2f2f642e73796d63622e636f6d2f727061301f0603551d230418301680145f60cf619055df8443148a602ab2f57af44318ef302b0603551d1f042430223020a01ea01c861a687474703a2f2f73732e73796d63622e636f6d2f73732e63726c305706082b06010505070101044b3049301f06082b060105050730018613687474703a2f2f73732e73796d63642e636f6d302606082b06010505073002861a687474703a2f2f73732e73796d63622e636f6d2f73732e6372743082017e060a2b06010401d6790204020482016e0482016a0168007700ddeb1d2b7a0d4fa6208b81ad8168707e2e8e9d01d55c888d3d11c4cdb6ecbecc0000014ff9542aaa00000403004830460221008c579fb270d2d17227517161a3e1bd08235f7357912f0509e781abc233100247022100a5e7dfaa35ffd47e06f6d3a241eaeba3d7aabbd2e30cc6990e0cd521a48248fa007500a4b90990b418581487bb13a2cc67700a3c359804f91bdfb8e377cd0ec80ddc100000014ff9542aed000004030046304402205de0ace4e55e1a4130fdef4406f7d48c41aed0f89a7109aa7d3848511551785b02203a0607ac8597ead7a05ba4014f0fcdcbf8e6841981ad06d1fcbfa3971863172000760068f698f81f6482be3a8ceeb9281d4cfc71515d6793d444d10a67acbb4f4ffbc40000014ff9542af50000040300473045022100ff2be0f169e5cfefe582ab4f486e882e3ee63e6e4564657d23f1cfc98212ecab02207020d4cd3ed99efd718414b9deba4654a3d8d2c179d906b21ea792390151033e'.decode('hex')
#calculate the SHA256 for later comparison
print SHA256.new(cert).hexdigest()

pubkey = load_publickey(FILETYPE_ASN1,key)
f = open("pub.pem","wb+")
f.write(dump_publickey(FILETYPE_PEM, pubkey))
f.close()
print "Pubkey: " + str(pubkey.bits()) + " bits,",
rsa = _lib.EVP_PKEY_get1_RSA(pubkey._pkey)
print str(_lib.RSA_size(rsa)) + " bytes."

#Got problem with pyOpenSSL to decrypt so use M2Crypto instead
#result = _lib.RSA_public_decrypt(len(encHash),encHash,decHash,rsa,_lib.RSA_PKCS1_PADDING)
rsa = M2Crypto.RSA.load_pub_key('pub.pem')
decHash = rsa.public_decrypt(encHash,M2Crypto.RSA.no_padding)
print "PKCS #1 data of signature\n", decHash.encode('hex')
#see rfc 3447 9.2 EMSA-PKCS1-v1_5
nextZero = decHash[2:].find("\x00") + 2
decHash = decHash[nextZero+1:]					#asn.1 DER-encoded
#extract actual data in asn.1 using Crypto.Util.asn1
der = asn1.DerSequence()