Skip to content

Instantly share code, notes, and snippets.

@SimonTheCoder
Last active March 16, 2023 09:17
Show Gist options
  • Save SimonTheCoder/51d30a2cd243d6f86591aef42af63b4a to your computer and use it in GitHub Desktop.
Save SimonTheCoder/51d30a2cd243d6f86591aef42af63b4a to your computer and use it in GitHub Desktop.
Scan a binary file, try to find x509 der certificates, then dump to files.
import OpenSSL.crypto as crypto
import sys
def progress_bar(current, total):
"""Print a progress bar to the console."""
progress = float(current) / float(total)
bar_length = 40
filled_length = int(round(bar_length * progress))
bar = '=' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r%s/%s [%s] %.2f%%' % (current, total, bar, progress * 100))
sys.stdout.flush()
# 读取DER格式的X.509数字证书文件
with open(sys.argv[1], 'rb') as cert_file:
cert_data = cert_file.read()
scan_count = 0
print("Scan start.")
while True:
#check if scan is over.
if len(cert_data) <= scan_count:
print("\nScan over.")
exit(0)
# print(f"trying offset:{scan_count}",)
# show the progress_bar
progress_bar(scan_count, len(cert_data))
try_cert = cert_data[scan_count:]
if try_cert[:2] != b'\x30\x82':
# print(f"trying offset:{scan_count}",)
scan_count += 1
continue
try:
# 解析X.509数字证书
x509_cert = crypto.load_certificate(crypto.FILETYPE_ASN1, try_cert)
# 读取证书信息
subject = x509_cert.get_subject()
issuer = x509_cert.get_issuer()
serial_number = x509_cert.get_serial_number()
not_before = x509_cert.get_notBefore()
not_after = x509_cert.get_notAfter()
public_key = x509_cert.get_pubkey()
# 输出证书信息
print('Subject:', subject)
print('Issuer:', issuer)
print('Serial number:', serial_number)
print('Not before:', not_before)
print('Not after:', not_after)
print('Public key:', public_key)
cert_binary_data = crypto.dump_certificate(crypto.FILETYPE_ASN1, x509_cert)
cert_size = len(cert_binary_data)
with open(f"cert@{scan_count}.der","wb") as f:
f.write(cert_binary_data)
scan_count=scan_count + cert_size
except Exception as e:
#print(e)
#print("Failed.")
scan_count = scan_count + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment