Debian Codegraph @

debian/tests/helpers/gen_rsa_key.py

raw symbols SCIP
1 import argparse
2 import time
3 import sys
4
5 # Use pycryptodome's RSA library
6 # See https://pycryptodome.readthedocs.io/en/latest/src/public_key/rsa.html#Crypto.PublicKey.RSA.construct # noqa: E501
7 from Cryptodome.PublicKey import RSA
8
9
10 KEY_ELEMENTS = ["PRIV_EXP", "PRIME_1", "PRIME_2", "PUB_EXP"]
11
12
13 def sparse_str_to_hex(s):
14 return int(s.replace('"', "").replace(" ", ""), 16)
15
16
17 def main(infile=None):
18 lines = []
19 # Checks, if interactive session or reading from a file
20 if sys.stdin.isatty():
21 if infile.name != "<stdin>":
22 # Reads specification file
23 with open(infile.name, "r") as f:
24 lines = f.readlines()
25 else:
26 exit("Supply data via STDIN or file!")
27 else:
28 lines = sys.stdin.readlines()
29
30 construct_key(lines)
31
32
33 def construct_key(lines):
34 keymaterial = {}
35
36 # Populates keymaterial
37 for line in lines:
38 # Tokenizes line
39 parts = line.split("=", 1)
40 name = parts[0]
41 val = parts[-1]
42
43 # Stores line in dict
44 if name in KEY_ELEMENTS:
45 keymaterial[name] = sparse_str_to_hex(val)
46
47 if "PRIME_1" in keymaterial and "PRIME_2" in keymaterial:
48 keymaterial["MODULUS"] = keymaterial["PRIME_1"] * keymaterial["PRIME_2"] # noqa: E501
49 else:
50 exit("Key specification is incomplete.")
51
52 # Constructs RSA key by given params
53 rsa_key = RSA.construct(
54 (
55 keymaterial["MODULUS"], # n
56 keymaterial["PUB_EXP"], # e
57 keymaterial["PRIV_EXP"], # d
58 keymaterial["PRIME_1"], # p
59 keymaterial["PRIME_2"], # q
60 )
61 )
62
63 # Assign it to a variable to keep it in memory
64 exported_rsa_key = rsa_key.exportKey() # noqa: F841
65
66 while True:
67 time.sleep(1)
68
69
70 def parse_args():
71 parser = argparse.ArgumentParser(
72 description="Construct a RSA key according to specified key material and sleep forever." # noqa: E501
73 )
74 parser.add_argument(
75 "keyspec", nargs="?", type=argparse.FileType("r"), default=sys.stdin
76 )
77 args = parser.parse_args()
78 return args
79
80
81 if __name__ == "__main__":
82 args = parse_args()
83 construct_key(args.keyspec)