How to use the xmlsec.Key function in xmlsec

To help you get started, we’ve selected a few xmlsec examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mehcode / python-xmlsec / tests / examples / test_decrypt.py View on Github external
def test_decrypt2():
    manager = xmlsec.KeysManager()
    filename = path.join(BASE_DIR, 'rsakey.pem')
    key = xmlsec.Key.from_memory(read_from_file(filename), xmlsec.KeyFormat.PEM, None)
    assert key is not None
    manager.add_key(key)

    enc_ctx = xmlsec.EncryptionContext(manager)

    root = parse_xml("enc2-res.xml")
    enc_data = xmlsec.tree.find_child(root, xmlsec.Node.ENCRYPTED_DATA, xmlsec.Namespace.ENC)
    assert enc_data is not None
    decrypted = enc_ctx.decrypt(enc_data)
    assert decrypted.text == "\ntest\n"
github mehcode / python-xmlsec / tests / examples / test_decrypt.py View on Github external
def test_decrypt1():
    manager = xmlsec.KeysManager()
    filename = path.join(BASE_DIR, 'rsakey.pem')
    key = xmlsec.Key.from_memory(read_from_file(filename), xmlsec.KeyFormat.PEM, None)
    assert key is not None
    manager.add_key(key)

    enc_ctx = xmlsec.EncryptionContext(manager)

    root = parse_xml("enc1-res.xml")
    enc_data = xmlsec.tree.find_child(root, "EncryptedData", xmlsec.Namespace.ENC)
    assert enc_data is not None
    decrypted = enc_ctx.decrypt(enc_data)
    assert decrypted.tag == "Data"

    compare("enc1-doc.xml", root)
github mehcode / python-xmlsec / tests / examples / test_encrypt.py View on Github external
manager.add_key(key)
    template = etree.Element("root")
    assert template is not None
    # Prepare for encryption
    enc_data = xmlsec.template.encrypted_data_create(
        template, xmlsec.Transform.AES128, type=xmlsec.EncryptionType.CONTENT, ns="xenc",
        mime_type="binary/octet-stream")

    xmlsec.template.encrypted_data_ensure_cipher_value(enc_data)
    key_info = xmlsec.template.encrypted_data_ensure_key_info(enc_data, ns="dsig")
    enc_key = xmlsec.template.add_encrypted_key(key_info, xmlsec.Transform.RSA_OAEP)
    xmlsec.template.encrypted_data_ensure_cipher_value(enc_key)

    # Encrypt!
    enc_ctx = xmlsec.EncryptionContext(manager)
    enc_ctx.key = xmlsec.Key.generate(xmlsec.KeyData.AES, 128, xmlsec.KeyDataType.SESSION)
    enc_data = enc_ctx.encrypt_binary(enc_data, b'test')
    assert enc_data is not None
    assert enc_data.tag == "{%s}%s" % (xmlsec.Namespace.ENC, xmlsec.Node.ENCRYPTED_DATA)
    print(xmlsec.Node.ENCRYPTION_METHOD)
    enc_method = xmlsec.tree.find_child(enc_data, xmlsec.Node.ENCRYPTION_METHOD, xmlsec.Namespace.ENC)
    assert enc_method is not None
    assert enc_method.get("Algorithm") == "http://www.w3.org/2001/04/xmlenc#aes128-cbc"
    key_info = xmlsec.tree.find_child(enc_data, xmlsec.Node.KEY_INFO, xmlsec.Namespace.DS)
    assert key_info is not None
    enc_method = xmlsec.tree.find_node(key_info, xmlsec.Node.ENCRYPTION_METHOD, xmlsec.Namespace.ENC)
    assert enc_method is not None
    assert enc_method.get("Algorithm") == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
    cipher_value = xmlsec.tree.find_node(key_info, xmlsec.Node.CIPHER_VALUE, xmlsec.Namespace.ENC)
    assert cipher_value is not None
github mehcode / python-xmlsec / tests / test_enc.py View on Github external
def check_decrypt(self, i, ):
        root = self.load_xml('enc%d-out.xml' % i)
        enc_data = xmlsec.tree.find_child(root, consts.NodeEncryptedData, consts.EncNs)
        self.assertIsNotNone(enc_data)

        manager = xmlsec.KeysManager()
        manager.add_key(xmlsec.Key.from_file(self.path("rsakey.pem"), format=consts.KeyDataFormatPem))
        ctx = xmlsec.EncryptionContext(manager)
        decrypted = ctx.decrypt(enc_data)
        self.assertIsNotNone(decrypted)
        self.assertEqual(self.load_xml("enc%d-in.xml" % i), root)
github CityOfNewYork / NYCOpenRecords / app / lib / onelogin / saml2 / utils.py View on Github external
if cert is None or cert == '':
                return False

            # Check if Reference URI is empty
            reference_elem = OneLogin_Saml2_XML.query(signature_node, '//ds:Reference')
            if len(reference_elem) > 0:
                if reference_elem[0].get('URI') == '':
                    reference_elem[0].set('URI', '#%s' % signature_node.getparent().get('ID'))

            if validatecert:
                manager = xmlsec.KeysManager()
                manager.load_cert_from_memory(cert, xmlsec.KeyFormat.CERT_PEM, xmlsec.KeyDataType.TRUSTED)
                dsig_ctx = xmlsec.SignatureContext(manager)
            else:
                dsig_ctx = xmlsec.SignatureContext()
                dsig_ctx.key = xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None)

            dsig_ctx.set_enabled_key_data([xmlsec.KeyData.X509])
            dsig_ctx.verify(signature_node)
            return True
        except xmlsec.Error as e:
            if debug:
                print(e)
github CityOfNewYork / NYCOpenRecords / app / lib / onelogin / saml2 / utils.py View on Github external
:param signature: The signature that will be validate
        :type: string

        :param cert: The pubic cert
        :type: string

        :param algorithm: Signature algorithm
        :type: string

        :param debug: Activate the xmlsec debug
        :type: bool
        """
        try:
            xmlsec.enable_debug_trace(debug)
            dsig_ctx = xmlsec.SignatureContext()
            dsig_ctx.key = xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None)

            sign_algorithm_transform_map = {
                OneLogin_Saml2_Constants.DSA_SHA1: xmlsec.Transform.DSA_SHA1,
                OneLogin_Saml2_Constants.RSA_SHA1: xmlsec.Transform.RSA_SHA1,
                OneLogin_Saml2_Constants.RSA_SHA256: xmlsec.Transform.RSA_SHA256,
                OneLogin_Saml2_Constants.RSA_SHA384: xmlsec.Transform.RSA_SHA384,
                OneLogin_Saml2_Constants.RSA_SHA512: xmlsec.Transform.RSA_SHA512
            }
            sign_algorithm_transform = sign_algorithm_transform_map.get(algorithm, xmlsec.Transform.RSA_SHA1)

            dsig_ctx.verify_binary(compat.to_bytes(signed_query),
                                   sign_algorithm_transform,
                                   compat.to_bytes(signature))
            return True
        except xmlsec.Error as e:
            if debug:
github dnet / pyxmlsec / xmlsec.py View on Github external
def cryptoAppKeyLoad(filename, format, pwd, pwdCallback, pwdCallbackCtx):
    """
    Reads key from filename.
    filename       : the key filename.
    format         : the key file format.
    pwd            : the key file password.
    pwdCallback    : the key password callback.
    pwdCallbackCtx : the user context for password callback.
    Returns        : the key or None if an error occurs.
    """
    ret = xmlsecmod.cryptoAppKeyLoad(filename, format, pwd,
                                     pwdCallback, pwdCallbackCtx)
    if ret is None: raise Error('xmlSecCryptoAppKeyLoad() failed')
    return Key(_obj=ret)
def cryptoAppPkcs12Load(filename, pwd, pwdCallback, pwdCallbackCtx):
github CityOfNewYork / NYCOpenRecords / src / onelogin / saml2 / utils.py View on Github external
root = OneLogin_Saml2_XML.make_root("{%s}container" % OneLogin_Saml2_Constants.NS_SAML)
        name_id = OneLogin_Saml2_XML.make_child(root, '{%s}NameID' % OneLogin_Saml2_Constants.NS_SAML)
        if sp_nq is not None:
            name_id.set('SPNameQualifier', sp_nq)
        name_id.set('Format', sp_format)
        if nq is not None:
            name_id.set('NameQualifier', nq)
        name_id.text = value

        if cert is not None:
            xmlsec.enable_debug_trace(debug)

            # Load the public cert
            manager = xmlsec.KeysManager()
            manager.add_key(xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None))

            # Prepare for encryption
            enc_data = xmlsec.template.encrypted_data_create(
                root, xmlsec.Transform.AES128, type=xmlsec.EncryptionType.ELEMENT, ns="xenc")

            xmlsec.template.encrypted_data_ensure_cipher_value(enc_data)
            key_info = xmlsec.template.encrypted_data_ensure_key_info(enc_data, ns="dsig")
            enc_key = xmlsec.template.add_encrypted_key(key_info, xmlsec.Transform.RSA_OAEP)
            xmlsec.template.encrypted_data_ensure_cipher_value(enc_key)

            # Encrypt!
            enc_ctx = xmlsec.EncryptionContext(manager)
            enc_ctx.key = xmlsec.Key.generate(xmlsec.KeyData.AES, 128, xmlsec.KeyDataType.SESSION)
            enc_data = enc_ctx.encrypt_xml(enc_data, name_id)
            return '' + compat.to_string(OneLogin_Saml2_XML.to_string(enc_data)) + ''
        else:
github dnet / pyxmlsec / xmlsec.py View on Github external
def keyGenerate(dataId, sizeBits, type):
    """
    Generates new key of requested klass dataId and type.
    dataId   : the requested key klass (rsa, dsa, aes, ...).
    sizeBits : the new key size (in bits!).
    type     : the new key type (session, permanent, ...).
    Returns  : the newly created key or None if an error occurs.
    """
    return Key(_obj=xmlsecmod.keyGenerate(dataId, sizeBits, type))
def keyGenerateByName(name, sizeBits, type):
github CityOfNewYork / NYCOpenRecords / app / lib / onelogin / saml2 / utils.py View on Github external
root = OneLogin_Saml2_XML.make_root("{%s}container" % OneLogin_Saml2_Constants.NS_SAML)
        name_id = OneLogin_Saml2_XML.make_child(root, '{%s}NameID' % OneLogin_Saml2_Constants.NS_SAML)
        if sp_nq is not None:
            name_id.set('SPNameQualifier', sp_nq)
        name_id.set('Format', sp_format)
        if nq is not None:
            name_id.set('NameQualifier', nq)
        name_id.text = value

        if cert is not None:
            xmlsec.enable_debug_trace(debug)

            # Load the public cert
            manager = xmlsec.KeysManager()
            manager.add_key(xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None))

            # Prepare for encryption
            enc_data = xmlsec.template.encrypted_data_create(
                root, xmlsec.Transform.AES128, type=xmlsec.EncryptionType.ELEMENT, ns="xenc")

            xmlsec.template.encrypted_data_ensure_cipher_value(enc_data)
            key_info = xmlsec.template.encrypted_data_ensure_key_info(enc_data, ns="dsig")
            enc_key = xmlsec.template.add_encrypted_key(key_info, xmlsec.Transform.RSA_OAEP)
            xmlsec.template.encrypted_data_ensure_cipher_value(enc_key)

            # Encrypt!
            enc_ctx = xmlsec.EncryptionContext(manager)
            enc_ctx.key = xmlsec.Key.generate(xmlsec.KeyData.AES, 128, xmlsec.KeyDataType.SESSION)
            enc_data = enc_ctx.encrypt_xml(enc_data, name_id)
            return '' + compat.to_string(OneLogin_Saml2_XML.to_string(enc_data)) + ''
        else: