codekingpro/portable-devtools
114k
1# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Utility functions."""
16
17import sys
18from optparse import OptionParser
19
20import rsa.key
21
22
23def private_to_public() -> None:
24 """Reads a private key and outputs the corresponding public key."""
25
26 # Parse the CLI options
27 parser = OptionParser(
28 usage="usage: %prog [options]",
29 description="Reads a private key and outputs the "
30 "corresponding public key. Both private and public keys use "
31 "the format described in PKCS#1 v1.5",
32 )
33
34 parser.add_option(
35 "-i",
36 "--input",
37 dest="infilename",
38 type="string",
39 help="Input filename. Reads from stdin if not specified",
40 )
41 parser.add_option(
42 "-o",
43 "--output",
44 dest="outfilename",
45 type="string",
46 help="Output filename. Writes to stdout of not specified",
47 )
48
49 parser.add_option(
50 "--inform",
51 dest="inform",
52 help="key format of input - default PEM",
53 choices=("PEM", "DER"),
54 default="PEM",
55 )
56
57 parser.add_option(
58 "--outform",
59 dest="outform",
60 help="key format of output - default PEM",
61 choices=("PEM", "DER"),
62 default="PEM",
63 )
64
65 (cli, cli_args) = parser.parse_args(sys.argv)
66
67 # Read the input data
68 if cli.infilename:
69 print(
70 "Reading private key from %s in %s format" % (cli.infilename, cli.inform),
71 file=sys.stderr,
72 )
73 with open(cli.infilename, "rb") as infile:
74 in_data = infile.read()
75 else:
76 print("Reading private key from stdin in %s format" % cli.inform, file=sys.stderr)
77 in_data = sys.stdin.read().encode("ascii")
78
79 assert type(in_data) == bytes, type(in_data)
80
81 # Take the public fields and create a public key
82 priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform)
83 pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e)
84
85 # Save to the output file
86 out_data = pub_key.save_pkcs1(cli.outform)
87
88 if cli.outfilename:
89 print(
90 "Writing public key to %s in %s format" % (cli.outfilename, cli.outform),
91 file=sys.stderr,
92 )
93 with open(cli.outfilename, "wb") as outfile:
94 outfile.write(out_data)
95 else:
96 print("Writing public key to stdout in %s format" % cli.outform, file=sys.stderr)
97 sys.stdout.write(out_data.decode("ascii"))
98 