def verify_assertion(assertion, public_key_str): u""" Проверка цифровой подписи утверждения по публичному ключу :param assertion: Утверждение (Assertion, xml) :type assertion: etree.ElementTree :param basestring public_key_str: публичный ключ подписи представленный в виде строки :return: признак успешной проверки подписи :rtype: bool :raise: XMLSigException - ошибка при проверке подписи """ if not xmldsig is None: with open(public_key_str, 'r') as public_key_file: public_key_data = public_key_file.read() public_key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_data) try: return xmldsig.verify(assertion.getroottree(), public_key) except xmldsig.XMLSigException as err: if err.message == "Is not signed xml!": return True else: raise err else: raise ImportError("Cant import xmldsig module.")
def main(): # 1. Read XML # ======== xml = open("samples/second-unsigned.xml").read() # 2. Load RSA private key for signatures # ================================== data = open("samples/privkey_1_rsa_2048.pem").read() key_dict = rsa_x509_pem.parse(data) key = rsa_x509_pem.get_key(key_dict) # 3. Generate key info: choose one: # ============================== # - Style #1: embed RSA public key into signature itself key_info_xml1 = xmldsig.key_info_xml_rsa(key_dict['modulus'], key_dict['publicExponent']) # - Style #2: embed matching certificate from file into signature cert_lines = open("samples/rsa_cert_1_2048.pem").readlines() cert = ''.join([s.strip() for s in cert_lines[1:-1]]) key_info_xml2 = xmldsig.key_info_xml_cert(cert, "SubjectName") # note: subject_name = SubjectName to match provided example "samples/second.xml" # - Assume Style #2... key_info_xml = key_info_xml2 # 4. Sign XML Document # ============================== f_priv = rsa_x509_pem.f_private(key) signed_xml = xmldsig.sign(xml, f_priv, key_info_xml, key.size(), "Name") print signed_xml # 5. Verify signature f_pub = rsa_x509_pem.f_public(key) is_verified = xmldsig.verify(signed_xml, f_pub, key.size()) assert(is_verified) print "OK."
def test_template_verification_short(self): result = xmldsig.verify(EXAMPLE_XML_SIGNED, PEM_FILE, 'foobar') self.assertTrue(result)