Contributed-under: TianoCore Contribution Agreement 1.0
[mirror_edk2.git] / BaseTools / Source / Python / Rsa2048Sha256Sign / Rsa2048Sha256GenerateKeys.py
CommitLineData
65ce860e
MK
1## @file\r
2# This tool can be used to generate new RSA 2048 bit private/public key pairs \r
3# in a PEM file format using OpenSSL command line utilities that are installed \r
4# on the path specified by the system environment variable OPENSSL_PATH.\r
5# This tool can also optionally write one or more SHA 256 hashes of 2048 bit \r
6# public keys to a binary file, write one or more SHA 256 hashes of 2048 bit \r
7# public keys to a file in a C structure format, and in verbose mode display \r
8# one or more SHA 256 hashes of 2048 bit public keys in a C structure format \r
9# on STDOUT.\r
10# This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013\r
11#\r
12# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.<BR>\r
13# This program and the accompanying materials\r
14# are licensed and made available under the terms and conditions of the BSD License\r
15# which accompanies this distribution. The full text of the license may be found at\r
16# http://opensource.org/licenses/bsd-license.php\r
17#\r
18# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
19# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
20#\r
21\r
22'''\r
23Rsa2048Sha256GenerateKeys\r
24'''\r
25\r
26import os\r
27import sys\r
28import argparse \r
29import subprocess\r
30\r
31if __name__ == '__main__':\r
32 #\r
33 # Save name of the program\r
34 #\r
35 ProgramName = sys.argv[0]\r
36 \r
37 #\r
38 # Print copyright \r
39 #\r
40 print '%s - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.' % (ProgramName)\r
41 \r
42 #\r
43 # Create command line argument parser object\r
44 # \r
45 parser = argparse.ArgumentParser(prog=ProgramName, usage='%(prog)s [options]', add_help=False)\r
46 group = parser.add_mutually_exclusive_group(required=True)\r
47 group.add_argument("-o", "--output", dest='OutputFile', type=argparse.FileType('wb'), metavar='filename', nargs='*', help="specify the output private key filename in PEM format")\r
48 group.add_argument("-i", "--input", dest='InputFile', type=argparse.FileType('rb'), metavar='filename', nargs='*', help="specify the input private key filename in PEM format")\r
49 parser.add_argument("--public-key-hash", dest='PublicKeyHashFile', type=argparse.FileType('wb'), help="specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in binary format")\r
50 parser.add_argument("--public-key-hash-c", dest='PublicKeyHashCFile', type=argparse.FileType('wb'), help="specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in C structure format")\r
51 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")\r
52 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")\r
53 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")\r
54 parser.add_argument("--version", dest='Version', action="store_true", help="display the program version and exit")\r
55 parser.add_argument("-h", "--help", dest='Help', action="help", help="display this help text")\r
56\r
57 #\r
58 # Parse command line arguments\r
59 # \r
60 args = parser.parse_args()\r
61\r
62 #\r
63 # Generate file path to Open SSL command\r
64 #\r
65 OpenSslCommand = 'openssl'\r
66 try:\r
67 OpenSslPath = os.environ['OPENSSL_PATH']\r
68 OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)\r
69 except:\r
70 pass\r
71\r
72 #\r
73 # Verify that Open SSL command is available\r
74 #\r
75 try:\r
76 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
77 except: \r
78 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'\r
79 sys.exit(1)\r
80 \r
81 Version = Process.communicate()\r
82 if Process.returncode <> 0:\r
83 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'\r
84 sys.exit(Process.returncode)\r
85 print Version[0]\r
86 \r
87 args.PemFileName = []\r
88 \r
89 #\r
90 # Check for output file argument\r
91 #\r
92 if args.OutputFile <> None:\r
93 for Item in args.OutputFile:\r
94 #\r
95 # Save PEM filename and close output file\r
96 #\r
97 args.PemFileName.append(Item.name)\r
98 Item.close()\r
99\r
100 #\r
101 # Generate private key and save it to output file in a PEM file format\r
102 #\r
103 Process = subprocess.Popen('%s genrsa -out %s 2048' % (OpenSslCommand, Item.name), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
104 Process.communicate()\r
105 if Process.returncode <> 0:\r
106 print 'ERROR: RSA 2048 key generation failed'\r
107 sys.exit(Process.returncode)\r
108 \r
109 #\r
110 # Check for input file argument\r
111 #\r
112 if args.InputFile <> None:\r
113 for Item in args.InputFile:\r
114 #\r
115 # Save PEM filename and close input file\r
116 #\r
117 args.PemFileName.append(Item.name)\r
118 Item.close()\r
119\r
120 PublicKeyHash = ''\r
121 for Item in args.PemFileName:\r
122 #\r
123 # Extract public key from private key into STDOUT\r
124 #\r
125 Process = subprocess.Popen('%s rsa -in %s -modulus -noout' % (OpenSslCommand, Item), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
126 PublicKeyHexString = Process.communicate()[0].split('=')[1].strip()\r
127 if Process.returncode <> 0:\r
128 print 'ERROR: Unable to extract public key from private key'\r
129 sys.exit(Process.returncode)\r
130 PublicKey = ''\r
131 for Index in range (0, len(PublicKeyHexString), 2):\r
132 PublicKey = PublicKey + chr(int(PublicKeyHexString[Index:Index + 2], 16))\r
133\r
134 #\r
135 # Generate SHA 256 hash of RSA 2048 bit public key into STDOUT\r
136 #\r
137 Process = subprocess.Popen('%s dgst -sha256 -binary' % (OpenSslCommand), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
138 Process.stdin.write (PublicKey)\r
139 PublicKeyHash = PublicKeyHash + Process.communicate()[0]\r
140 if Process.returncode <> 0:\r
141 print 'ERROR: Unable to extract SHA 256 hash of public key'\r
142 sys.exit(Process.returncode)\r
143\r
144 #\r
145 # Write SHA 256 hash of 2048 bit binary public key to public key hash file\r
146 #\r
147 try:\r
148 args.PublicKeyHashFile.write (PublicKeyHash)\r
149 args.PublicKeyHashFile.close ()\r
150 except:\r
151 pass\r
152\r
153 #\r
154 # Convert public key hash to a C structure string\r
155 #\r
156 PublicKeyHashC = '{'\r
157 for Item in PublicKeyHash:\r
158 PublicKeyHashC = PublicKeyHashC + '0x%02x, ' % (ord(Item))\r
159 PublicKeyHashC = PublicKeyHashC[:-2] + '}'\r
160 \r
161 #\r
162 # Write SHA 256 of 2048 bit binary public key to public key hash C structure file\r
163 #\r
164 try:\r
165 args.PublicKeyHashCFile.write (PublicKeyHashC)\r
166 args.PublicKeyHashCFile.close ()\r
167 except:\r
168 pass\r
169 \r
170 #\r
171 # If verbose is enabled display the public key in C structure format\r
172 #\r
173 if args.Verbose:\r
174 print 'PublicKeySha256 = ' + PublicKeyHashC \r