xref: /aosp_15_r20/external/cronet/net/data/ssl/scripts/generate-fuzzer-cert-include.py (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1*6777b538SAndroid Build Coastguard Worker# Copyright 2017 The Chromium Authors
2*6777b538SAndroid Build Coastguard Worker# Use of this source code is governed by a BSD-style license that can be
3*6777b538SAndroid Build Coastguard Worker# found in the LICENSE file.
4*6777b538SAndroid Build Coastguard Worker
5*6777b538SAndroid Build Coastguard Worker"""Generate C/C++ source from certificate.
6*6777b538SAndroid Build Coastguard Worker
7*6777b538SAndroid Build Coastguard WorkerUsage:
8*6777b538SAndroid Build Coastguard Worker  generate-spdy-session-fuzzer-includes.py input_filename output_filename
9*6777b538SAndroid Build Coastguard Worker
10*6777b538SAndroid Build Coastguard WorkerLoad the PEM block from `input_filename` certificate, perform base64 decoding
11*6777b538SAndroid Build Coastguard Workerand hex encoding, and save it in `output_filename` so that it can be directly
12*6777b538SAndroid Build Coastguard Workerincluded from C/C++ source as a char array.
13*6777b538SAndroid Build Coastguard Worker"""
14*6777b538SAndroid Build Coastguard Worker
15*6777b538SAndroid Build Coastguard Workerimport base64
16*6777b538SAndroid Build Coastguard Workerimport re
17*6777b538SAndroid Build Coastguard Workerimport sys
18*6777b538SAndroid Build Coastguard Workerimport textwrap
19*6777b538SAndroid Build Coastguard Worker
20*6777b538SAndroid Build Coastguard Workerinput_filename = sys.argv[1]
21*6777b538SAndroid Build Coastguard Workeroutput_filename = sys.argv[2]
22*6777b538SAndroid Build Coastguard Worker
23*6777b538SAndroid Build Coastguard Worker# Load PEM block.
24*6777b538SAndroid Build Coastguard Workerwith open(input_filename, 'r') as f:
25*6777b538SAndroid Build Coastguard Worker  match = re.search(
26*6777b538SAndroid Build Coastguard Worker      r"-----BEGIN CERTIFICATE-----\n(.+)-----END CERTIFICATE-----\n", f.read(),
27*6777b538SAndroid Build Coastguard Worker      re.DOTALL)
28*6777b538SAndroid Build Coastguard Workertext = match.group(1)
29*6777b538SAndroid Build Coastguard Worker
30*6777b538SAndroid Build Coastguard Worker# Perform Base64 decoding.
31*6777b538SAndroid Build Coastguard Workerdata = base64.b64decode(text)
32*6777b538SAndroid Build Coastguard Worker
33*6777b538SAndroid Build Coastguard Worker# Hex format data.
34*6777b538SAndroid Build Coastguard Workerhex_encoded = ", ".join("0x{:02x}".format(c) for c in bytearray(data))
35*6777b538SAndroid Build Coastguard Worker
36*6777b538SAndroid Build Coastguard Worker# Write into |output_filename| wrapped at 80 columns.
37*6777b538SAndroid Build Coastguard Workerwith open(output_filename, 'w') as f:
38*6777b538SAndroid Build Coastguard Worker  f.write(textwrap.fill(hex_encoded, 80))
39*6777b538SAndroid Build Coastguard Worker  f.write("\n")
40