def test_ecdsa_signverify(curve, hashname): key_object = objects.ECCKey(0xE100) pkey, _ = crypto.generate_pair(key_object, curve=curve) key_object_fail = objects.ECCKey(0xE101) pkey_fail, _ = crypto.generate_pair(key_object_fail, curve=curve) ha = hashname s = crypto.ecdsa_sign(key_object, tbs_str) print('[{}]'.format(', '.join(hex(x) for x in list(s.signature)))) # Preparing a PublicKeyInfo pubkey_info = keys.PublicKeyInfo.load(pkey) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) ecdsa_verify(public, s.signature, tbs_str, ha) # Assert wrong text with pytest.raises(SignatureError): ecdsa_verify(public, s.signature, tbs_str_fail, ha) # Assert wrong key with pytest.raises(SignatureError): # Preparing a PublicKeyInfo pubkey_info = keys.PublicKeyInfo.load(pkey_fail) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) ecdsa_verify(public, s.signature, tbs_str, ha)
def test_dump_public(self): public = asymmetric.load_public_key( os.path.join(fixtures_dir, 'keys/test.crt')) pem_serialized = asymmetric.dump_public_key(public) public_reloaded = asymmetric.load_public_key(pem_serialized) self.assertIsInstance(public_reloaded, asymmetric.PublicKey) self.assertEqual('rsa', public_reloaded.algorithm)
def test_ec_generate(self): public, private = asymmetric.generate_pair('ec', curve='secp256r1') self.assertEqual('ec', public.algorithm) self.assertEqual('secp256r1', public.asn1.curve[1]) original_data = b'This is data to sign' signature = asymmetric.ecdsa_sign(private, original_data, 'sha1') self.assertIsInstance(signature, byte_cls) asymmetric.ecdsa_verify(public, signature, original_data, 'sha1') raw_public = asymmetric.dump_public_key(public) asymmetric.load_public_key(raw_public) raw_private = asymmetric.dump_private_key(private, None) asymmetric.load_private_key(raw_private, None)
def test_dsa_generate(self): public, private = asymmetric.generate_pair('dsa', bit_size=1024) self.assertEqual('dsa', public.algorithm) self.assertEqual(1024, public.bit_size) original_data = b'This is data to sign' signature = asymmetric.dsa_sign(private, original_data, 'sha1') self.assertIsInstance(signature, byte_cls) asymmetric.dsa_verify(public, signature, original_data, 'sha1') raw_public = asymmetric.dump_public_key(public) asymmetric.load_public_key(raw_public) raw_private = asymmetric.dump_private_key(private, None) asymmetric.load_private_key(raw_private, None)
def test_ecdsa_p256_signverify(): LOGGER.info( 'Sign data with newly generated NIST P-256 key and verify result') setup_keys() ha = 'sha256' s = ecdsa.sign(pytest.p256, pytest.tbs_str) print('[{}]'.format(', '.join(hex(x) for x in list(s.signature)))) # Preparing an algoroithm pubkey_alg = keys.PublicKeyAlgorithm({ 'algorithm': keys.PublicKeyAlgorithmId(pytest.p256.algorithm), 'parameters': keys.ECDomainParameters(name='named', value=pytest.p256.curve) }) # Preparing a PublicKeyInfo pubkey_asn1 = core.BitString.load(pytest.p256.pkey) pubkey_info = keys.PublicKeyInfo({ 'algorithm': pubkey_alg, 'public_key': pubkey_asn1.cast(keys.ECPointBitString) }) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) ecdsa_verify(public, s.signature, pytest.tbs_str, ha) # Assert wrong text with pytest.raises(SignatureError): ecdsa_verify(public, s.signature, pytest.tbs_str_fail, ha) # Assert wrong key with pytest.raises(SignatureError): # Preparing a PublicKeyInfo pubkey_asn1 = core.BitString.load(pytest.p256_fail.pkey) pubkey_info = keys.PublicKeyInfo({ 'algorithm': pubkey_alg, 'public_key': pubkey_asn1.cast(keys.ECPointBitString) }) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) ecdsa_verify(public, s.signature, pytest.tbs_str, ha)
def verify_csr(csr): """ Verifies the signature on a CertificationRequest. Returns True or False. May raise a ValueError if the key algorithm is unknown. """ signature_algo = csr['signature_algorithm'].signature_algo hash_algo = csr['signature_algorithm'].hash_algo if signature_algo == 'rsassa_pkcs1v15': verify_func = asymmetric.rsa_pkcs1v15_verify elif signature_algo == 'dsa': verify_func = asymmetric.dsa_verify elif signature_algo == 'ecdsa': verify_func = asymmetric.ecdsa_verify else: raise ValueError("Unable to verify the CertificateList since the signature uses the unsupported algorithm %s", signature_algo) try: key_object = asymmetric.load_public_key(csr['certification_request_info']['subject_pk_info']) verify_func( key_object, csr['signature'].native, csr['certification_request_info'].dump(), hash_algo ) except (SignatureError): valid = False else: valid = True return valid
def test_rsa_raw_verify(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'rsa_signature_raw'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test.crt')) asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'raw')
def test_ecdsa_verify(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'ecdsa_signature'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-public-ec-named.key')) asymmetric.ecdsa_verify(public, signature, original_data, 'sha1')
def test_public_key_ec_attributes(self): pub_key = asymmetric.load_public_key( os.path.join(fixtures_dir, 'keys/test-public-ec-named.key')) self.assertEqual(256, pub_key.bit_size) self.assertEqual(32, pub_key.byte_size) self.assertEqual('secp256r1', pub_key.curve) self.assertEqual('ec', pub_key.algorithm)
def self_enroll(skip_notify=False): assert os.getuid() == 0 and os.getgid( ) == 0, "Can self-enroll only as root" from certidude import const, config common_name = const.FQDN os.umask(0o0177) try: path, buf, cert, signed, expires = get_signed(common_name) self_public_key = asymmetric.load_public_key(path) private_key = asymmetric.load_private_key(config.SELF_KEY_PATH) except FileNotFoundError: # certificate or private key not found click.echo("Generating private key for frontend: %s" % config.SELF_KEY_PATH) with open(config.SELF_KEY_PATH, 'wb') as fh: if public_key.algorithm == "ec": self_public_key, private_key = asymmetric.generate_pair( "ec", curve=public_key.curve) elif public_key.algorithm == "rsa": self_public_key, private_key = asymmetric.generate_pair( "rsa", bit_size=public_key.bit_size) else: raise NotImplemented( "CA certificate public key algorithm %s not supported" % public_key.algorithm) fh.write(asymmetric.dump_private_key(private_key, None)) else: now = datetime.utcnow() if now + timedelta(days=1) < expires: click.echo( "Certificate %s still valid, delete to self-enroll again" % path) return builder = CSRBuilder({"common_name": common_name}, self_public_key) request = builder.build(private_key) pid = os.fork() if not pid: from certidude import authority, config from certidude.common import drop_privileges drop_privileges() assert os.getuid() != 0 and os.getgid() != 0 path = os.path.join(config.REQUESTS_DIR, common_name + ".pem") click.echo("Writing certificate signing request for frontend: %s" % path) with open(path, "wb") as fh: fh.write( pem_armor_csr(request)) # Write CSR with certidude permissions authority.sign(common_name, skip_notify=skip_notify, skip_push=True, overwrite=True, profile=config.PROFILES["srv"]) click.echo("Frontend certificate signed") sys.exit(0) else: os.waitpid(pid, 0) os.system("systemctl reload nginx")
def test_rsa_raw_verify_fail(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'rsa_signature_raw'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test.crt')) with self.assertRaises(errors.SignatureError): asymmetric.rsa_pkcs1v15_verify(public, signature, original_data + b'1', 'raw')
def test_ec_public_key_attr(self): private = asymmetric.load_private_key( os.path.join(fixtures_dir, 'keys/test-ec-named.key')) public = asymmetric.load_public_key( os.path.join(fixtures_dir, 'keys/test-ec-named.crt')) computed_public = private.public_key self.assertEqual(public.asn1.dump(), computed_public.asn1.dump())
def test_dsa_verify_fail(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'dsa_signature'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-dsa-1024.crt')) with self.assertRaises(errors.SignatureError): asymmetric.dsa_verify(public, signature, original_data + b'1', 'sha1')
def test_rsa_verify_key_size_mismatch(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'rsa_signature'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-4096.crt')) with self.assertRaises(errors.SignatureError): asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'sha1')
def test_ecdsa_sign(self): original_data = b'This is data to sign' private = asymmetric.load_private_key(os.path.join(fixtures_dir, 'keys/test-ec-named.key')) public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-ec-named.crt')) signature = asymmetric.ecdsa_sign(private, original_data, 'sha1') self.assertIsInstance(signature, byte_cls) asymmetric.ecdsa_verify(public, signature, original_data, 'sha1')
def do_run(): original_data = b'This is data to sign' private = asymmetric.load_private_key(os.path.join(fixtures_dir, 'keys/test-dsa.key')) public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-dsa.crt')) signature = asymmetric.dsa_sign(private, original_data, 'sha256') self.assertIsInstance(signature, byte_cls) asymmetric.dsa_verify(public, signature, original_data, 'sha256')
def test_rsa_raw_sign(self): original_data = b'This is data to sign!' private = asymmetric.load_private_key(os.path.join(fixtures_dir, 'keys/test.key')) public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test.crt')) signature = asymmetric.rsa_pkcs1v15_sign(private, original_data, 'raw') self.assertIsInstance(signature, byte_cls) asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'raw')
def test_dsa_verify_key_size_mismatch(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'dsa_signature'), 'rb') as f: signature = f.read() public = asymmetric.load_public_key( os.path.join(fixtures_dir, 'keys/test-dsa-512.crt')) with self.assertRaises(errors.SignatureError): asymmetric.dsa_verify(public, signature, original_data, 'sha1')
def test_ec_fingerprints(self): private = asymmetric.load_private_key( os.path.join(fixtures_dir, 'keys/test-ec-named.key')) public = asymmetric.load_public_key( os.path.join(fixtures_dir, 'keys/test-ec-named.crt')) self.assertIsInstance(private.fingerprint, byte_cls) self.assertIsInstance(public.fingerprint, byte_cls) self.assertEqual(private.fingerprint, public.fingerprint)
def self_enroll(): assert os.getuid() == 0 and os.getgid( ) == 0, "Can self-enroll only as root" from certidude import const common_name = const.FQDN directory = os.path.join("/var/lib/certidude", const.FQDN) self_key_path = os.path.join(directory, "self_key.pem") try: path, buf, cert, signed, expires = get_signed(common_name) self_public_key = asymmetric.load_public_key(path) private_key = asymmetric.load_private_key(self_key_path) except FileNotFoundError: # certificate or private key not found with open(self_key_path, 'wb') as fh: if public_key.algorithm == "ec": self_public_key, private_key = asymmetric.generate_pair( "ec", curve=public_key.curve) elif public_key.algorithm == "rsa": self_public_key, private_key = asymmetric.generate_pair( "rsa", bit_size=public_key.bit_size) else: NotImplemented fh.write(asymmetric.dump_private_key(private_key, None)) else: now = datetime.utcnow() if now + timedelta(days=1) < expires: click.echo( "Certificate %s still valid, delete to self-enroll again" % path) return builder = CSRBuilder({"common_name": common_name}, self_public_key) request = builder.build(private_key) pid = os.fork() if not pid: from certidude import authority from certidude.common import drop_privileges drop_privileges() assert os.getuid() != 0 and os.getgid() != 0 path = os.path.join(directory, "requests", common_name + ".pem") click.echo("Writing request to %s" % path) with open(path, "wb") as fh: fh.write( pem_armor_csr(request)) # Write CSR with certidude permissions authority.sign(common_name, skip_push=True, overwrite=True, profile=config.PROFILES["srv"]) sys.exit(0) else: os.waitpid(pid, 0) if os.path.exists("/etc/systemd"): os.system("systemctl reload nginx") else: os.system("service nginx reload")
def test_rsa_oaep_encrypt(self): original_data = b'This is data to encrypt' private = asymmetric.load_private_key(os.path.join(fixtures_dir, 'keys/test.key')) public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test.crt')) ciphertext = asymmetric.rsa_oaep_encrypt(public, original_data) self.assertIsInstance(ciphertext, byte_cls) plaintext = asymmetric.rsa_oaep_decrypt(private, ciphertext) self.assertEqual(original_data, plaintext)
def __init__(self, der_string=None, public_key=None): if public_key is None: self._public_key = keys.parse_public(der_string) else: self._public_key = public_key self._oscrypto_public_key = asymmetric.load_public_key( source=self._public_key) self._crypto_public_key = serialization.load_der_public_key( data=self.to_der(), backend=default_backend())
def run(self): self.running = True while self.running: time.sleep(0.01) readable, writable, exceptions = select.select( self.socks, [], [], 0) for readableSocket in readable: if readableSocket == self.server: client, addr = self.server.accept() self.socks.append(client) self.waitingPublicKey.append(client) client.send(self.pair[0].asn1.dump()) else: try: data = readableSocket.recv(2048) except ConnectionResetError: data = 0 if data: if self.waitingPublicKey.__contains__(readableSocket): clientPubKey = asymmetric.load_public_key(data) rand = binascii.b2a_hex(os.urandom(3)) user = User("usr_" + rand.decode("ascii"), readableSocket, clientPubKey) self.all_but(user, user.username + " has joined.") self.users[str( readableSocket.getpeername()[1])] = user self.waitingPublicKey.remove(readableSocket) else: data = self.getMessage(data) user = self.users[str( readableSocket.getpeername()[1])] isCommand = data.startswith("/") if isCommand: result = "" args = data.split(" ") if data.startswith("/nick"): result = self.command_setNick(user, args) elif data.startswith("/who"): result = self.command_who(user, args) else: result = "Unknown command." if result != "": self.sendTo(user, result) else: msg = "[" + user.username + "]" + data self.all_but(user, msg) else: user = self.users[str(readableSocket.getpeername()[1])] del self.users[str(readableSocket.getpeername()[1])] readableSocket.close() self.socks.remove(readableSocket) self.all_but(readableSocket, user.username + " disconnected.")
def pubkey_xml_to_pem(xml): der = pubkey_xml_to_der(xml) b64 = b64encode(der).decode("ascii") pem = "\n".join([ "-----BEGIN PUBLIC KEY-----", *re.findall(r".{1,64}", b64), "-----END PUBLIC KEY-----" ]) # load and dump as both a form of validation and normalization pem = pem.encode("ascii") bpem = dump_public_key(load_public_key(pem), encoding="pem") return bpem.decode("ascii")
def test_rsa_generate(self): public, private = asymmetric.generate_pair('rsa', bit_size=2048) self.assertEqual('rsa', public.algorithm) self.assertEqual(2048, public.bit_size) original_data = b'This is data to sign' signature = asymmetric.rsa_pkcs1v15_sign(private, original_data, 'sha1') self.assertIsInstance(signature, byte_cls) asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'sha1') raw_public = asymmetric.dump_public_key(public) asymmetric.load_public_key(raw_public) raw_private = asymmetric.dump_private_key(private, None) asymmetric.load_private_key(raw_private, None) self.assertIsInstance(private.fingerprint, byte_cls) self.assertIsInstance(public.fingerprint, byte_cls) self.assertEqual(private.fingerprint, public.fingerprint)
def test_terrible_hybrid_file_encryption_app(self): # Proof of concept code only! import io from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt from oscrypto.symmetric import ( aes_cbc_pkcs7_encrypt, aes_cbc_pkcs7_decrypt, ) # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = load_public_key(encode_rsa_public_key(pub)) key = self.session.generate_random(256) iv = self.session.generate_random(128) source = b'This is my amazing file' with io.BytesIO() as dest: # Write a 128-byte header containing our key and our IV # strictly speaking we don't need to keep the IV secure but # we may as well. # # FIXME: Because this is RSA 1.5, we should fill the rest of the # frame with nonsense self.assertEqual(dest.write(rsa_pkcs1v15_encrypt(pub, key + iv)), 128) _, ciphertext = aes_cbc_pkcs7_encrypt(key, source, iv) dest.write(ciphertext) # Time passes dest.seek(0) # Look up our private key priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) # Read the header header = dest.read(priv.key_length // 8) header = priv.decrypt(header, mechanism=Mechanism.RSA_PKCS) # The first 32 bytes is our key key, header = header[:32], header[32:] # The next 16 bytes is the IV iv = header[:16] # We can ignore the rest plaintext = aes_cbc_pkcs7_decrypt(key, dest.read(), iv) self.assertEqual(source, plaintext)
def test_2k_signverify(): k1, k2 = setup_keys_2k() ha = 'sha256' s = crypto.pkcs1v15_sign(k1, pytest.tbs_str) print('[{}]'.format(', '.join(hex(x) for x in list(s.signature)))) pubkey_info = keys.PublicKeyInfo.load(pytest.twok) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str, ha) # Assert wrong text with pytest.raises(SignatureError): rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str_fail, ha) # Assert wrong key with pytest.raises(SignatureError): pubkey_info = keys.PublicKeyInfo.load(pytest.twok_fail) public = load_public_key(pubkey_info) rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str, ha)
def test_1k_signverify(): LOGGER.info('Sign data with newly generated RSA1k key and verify result') setup_keys_1k() ha = 'sha256' s = rsassa.sign(pytest.onek, pytest.tbs_str) print('[{}]'.format(', '.join(hex(x) for x in list(s.signature)))) pubkey_info = keys.PublicKeyInfo.load(pytest.onek.pkey) # Load a public key into the oscrypto engine to using it in the verify function public = load_public_key(pubkey_info) rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str, ha) # Assert wrong text with pytest.raises(SignatureError): rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str_fail, ha) # Assert wrong key with pytest.raises(SignatureError): pubkey_info = keys.PublicKeyInfo.load(pytest.onek_fail.pkey) public = load_public_key(pubkey_info) rsa_pkcs1v15_verify(public, s.signature, pytest.tbs_str, ha)
def verify(self, pubkey): self.check_valid() with open(self.filepath, 'rb') as zipfile: zipfile.seek(0, os.SEEK_SET) message = zipfile.read(self.signed_len) zipfile.seek(-self.signature_start, os.SEEK_END) signature_size = self.signature_start - FOOTER_SIZE signature_raw = zipfile.read(signature_size) sig = ContentInfo.load(signature_raw)['content']['signer_infos'][0] sig_contents = sig['signature'].contents sig_type = DigestAlgorithmId.map( sig['digest_algorithm']['algorithm'].dotted) with open(pubkey, 'rb') as keyfile: keydata = load_public_key(keyfile.read()) return rsa_pkcs1v15_verify(keydata, sig_contents, message, sig_type)
def verify_signature(self, signature_algorithm, signature, cert, data): pubkey = asymmetric.load_public_key(cert.public_key).unwrap().dump() rsakey = RSA.importKey(pubkey) signer = PKCS1_v1_5.new(rsakey) if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS: digest = \ SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS[ signature_algorithm].new() else: # the last resort. should not happen. digest = SHA1.new() digest.update(data.dump()) if not signer.verify(digest, signature): raise RevocationCheckError(msg="Failed to verify the signature", errno=ER_INVALID_OCSP_RESPONSE)
def test_dsa_verify_fail_each_byte(self): with open(os.path.join(fixtures_dir, 'message.txt'), 'rb') as f: original_data = f.read() with open(os.path.join(fixtures_dir, 'dsa_signature'), 'rb') as f: original_signature = f.read() public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-dsa-1024.crt')) for i in range(0, len(original_signature)): if i == 0: signature = b'\xab' + original_signature[1:] elif i == len(original_signature) - 1: signature = original_signature[0:-1] + b'\xab' else: signature = original_signature[0:i] + b'\xab' + original_signature[i+1:] with self.assertRaises(errors.SignatureError): asymmetric.dsa_verify(public, signature, original_data+ b'1', 'sha1')
def _validate_cms_signature(sig_blob: SignatureBlob, cd_hash: bytes): assert sig_blob.cms signed_data = sig_blob.cms["content"] assert isinstance(signed_data, SignedData) assert len(signed_data["signer_infos"]) == 1 # Get certificates cert_chain = [] for cert in signed_data["certificates"]: c = cert.chosen assert isinstance(c, Certificate) cert_chain.append(c) # Get algorithms used signer_info = signed_data["signer_infos"][0] digest_alg = signer_info["digest_algorithm"]["algorithm"].native sig_alg = signer_info["signature_algorithm"]["algorithm"].native # Get message and signature signed_attrs = signer_info["signed_attrs"] sig = signer_info["signature"].contents # Check the hash of CodeDirectory matches what is in the signature message_digest = None for attr in sig_blob.cms["content"]["signer_infos"][0]["signed_attrs"]: if attr["type"].native == "message_digest": message_digest = attr["values"][0].native if message_digest != cd_hash: raise Exception( f"CodeDirectory Hash mismatch. Expected {message_digest.hex()}, Calculated {cd_hash.hex()}" ) if message_digest is None: raise Exception("message_digest not found in signature") # Validate the certificate chain validation_context = ValidationContext( trust_roots=APPLE_ROOTS, allow_fetching=False, additional_critical_extensions=APPLE_CERT_CRIT_EXTS, ) validator = CertificateValidator(cert_chain[-1], cert_chain[0:-1], validation_context) validator.validate_usage({"digital_signature"}, {"code_signing"}) # Check the signature pubkey = asymmetric.load_public_key(cert_chain[-1].public_key) signed_msg = _sort_attributes(signed_attrs).dump() asymmetric.rsa_pkcs1v15_verify(pubkey, sig, signed_msg, digest_alg)
def public_encrypt(key, data, oaep): """ public key encryption using rsa with pkcs1-oaep padding. returns the base64-encoded encrypted data data: the data to be encrypted, bytes key: pem-formatted key string or bytes oaep: whether to use oaep padding or not """ if isinstance(key, str): key = key.encode("ascii") pubkey = load_public_key(key) if oaep: encrypted = rsa_oaep_encrypt(pubkey, data) else: encrypted = rsa_pkcs1v15_encrypt(pubkey, data) return b64encode(encrypted).decode("ascii")
def __init__(self, apk): self.is_v1 = apk.is_signed_v1() self.is_v2 = apk.is_signed_v2() self.is_v3 = apk.is_signed_v3() certs = set( apk.get_certificates_der_v3() + apk.get_certificates_der_v2() + [apk.get_certificate_der(x) for x in apk.get_signature_names()]) for cert in certs: # print(type(cert)) # print(type(x509_cert)) self.certificates.append(Certificate(cert)) pkeys = set(apk.get_public_keys_der_v3() + apk.get_public_keys_der_v2()) for public_key in pkeys: x509_public_key = asymmetric.load_public_key(public_key) self.public_keys.append(PublicKey(x509_public_key))
def test_load_incomplete_dsa_cert(self): with self.assertRaises(errors.IncompleteAsymmetricKeyError): asymmetric.load_public_key(os.path.join(fixtures_dir, 'DSAParametersInheritedCACert.crt'))
def load_public(name): return asymmetric.load_public_key(path.join( certs_dir, '{}.pubkey'.format(name) ))
def test_public_key_attributes(self): pub_key = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-public-rsa.key')) self.assertEqual(2048, pub_key.bit_size) self.assertEqual(256, pub_key.byte_size) self.assertEqual('rsa', pub_key.algorithm)
def test_public_key_ec_attributes(self): pub_key = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-public-ec-named.key')) self.assertEqual(256, pub_key.bit_size) self.assertEqual(32, pub_key.byte_size) self.assertEqual('secp256r1', pub_key.curve) self.assertEqual('ec', pub_key.algorithm)
def test_dump_public(self): public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test.crt')) pem_serialized = asymmetric.dump_public_key(public) public_reloaded = asymmetric.load_public_key(pem_serialized) self.assertIsInstance(public_reloaded, asymmetric.PublicKey) self.assertEqual('rsa', public_reloaded.algorithm)