Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
2
Indexable
Never
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cryptography import x509

def load_private_keys(file):
    with open(file, 'r') as f:
        keys = f.read().split('-----END RSA PRIVATE KEY-----')
        keys = [k + '-----END RSA PRIVATE KEY-----' for k in keys[:-1]]  # reattach the end marker
    return [serialization.load_pem_private_key(k.encode(), password=None, backend=default_backend()) for k in keys]

def load_certificate(file):
    with open(file, 'rb') as f:
        cert = x509.load_pem_x509_certificate(f.read(), default_backend())
    return cert

def find_matching_key(cert, private_keys):
    cert_public_key = cert.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    for i, key in enumerate(private_keys):
        key_public_key = key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        if key_public_key == cert_public_key:
            return i, key
    return None, None

# replace these with your actual file paths
certificate_file = '/path/to/certificate.pem'
private_keys_file = '/path/to/private_keys.pem'

certificate = load_certificate(certificate_file)
private_keys = load_private_keys(private_keys_file)

index, matching_key = find_matching_key(certificate, private_keys)

if matching_key is not None:
    print(f'Matching key found at index {index}:')
    print(matching_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    ).decode())
else:
    print('No matching key found.')