]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py
BaseTools: Handle the bytes and str difference
[mirror_edk2.git] / BaseTools / Source / Python / Rsa2048Sha256Sign / Rsa2048Sha256GenerateKeys.py
CommitLineData
65ce860e 1## @file\r
f7496d71
LG
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
65ce860e 4# on the path specified by the system environment variable OPENSSL_PATH.\r
f7496d71
LG
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
65ce860e
MK
9# on STDOUT.\r
10# This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013\r
11#\r
128d435f 12# Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR>\r
65ce860e
MK
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
1ccc4d89 25from __future__ import print_function\r
65ce860e
MK
26\r
27import os\r
28import sys\r
f7496d71 29import argparse\r
65ce860e 30import subprocess\r
c9df168f
MK
31from Common.BuildVersion import gBUILD_VERSION\r
32\r
33#\r
34# Globals for help information\r
35#\r
36__prog__ = 'Rsa2048Sha256GenerateKeys'\r
37__version__ = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)\r
f7496d71 38__copyright__ = 'Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.'\r
c9df168f
MK
39__usage__ = '%s [options]' % (__prog__)\r
40\r
65ce860e
MK
41\r
42if __name__ == '__main__':\r
65ce860e
MK
43 #\r
44 # Create command line argument parser object\r
f7496d71 45 #\r
56ad03a5 46 parser = argparse.ArgumentParser(prog=__prog__, usage=__usage__, description=__copyright__, conflict_handler='resolve')\r
65ce860e 47 group = parser.add_mutually_exclusive_group(required=True)\r
56ad03a5 48 group.add_argument("--version", action='version', version=__version__)\r
65ce860e
MK
49 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
50 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
51 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
52 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
53 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")\r
54 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")\r
ccaa7754 55 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0, 10), default=0, help="set debug level")\r
65ce860e
MK
56\r
57 #\r
58 # Parse command line arguments\r
f7496d71 59 #\r
65ce860e
MK
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
fcdb928a
YZ
69 if ' ' in OpenSslCommand:\r
70 OpenSslCommand = '"' + OpenSslCommand + '"'\r
65ce860e
MK
71 except:\r
72 pass\r
73\r
74 #\r
75 # Verify that Open SSL command is available\r
76 #\r
77 try:\r
8a0933f4 78 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
f7496d71 79 except:\r
72443dd2 80 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')\r
65ce860e 81 sys.exit(1)\r
f7496d71 82\r
65ce860e 83 Version = Process.communicate()\r
87d2afd0 84 if Process.returncode != 0:\r
72443dd2 85 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')\r
65ce860e 86 sys.exit(Process.returncode)\r
d943b0c3 87 print(Version[0].decode())\r
f7496d71 88\r
65ce860e 89 args.PemFileName = []\r
f7496d71 90\r
65ce860e
MK
91 #\r
92 # Check for output file argument\r
93 #\r
128d435f 94 if args.OutputFile is not None:\r
65ce860e
MK
95 for Item in args.OutputFile:\r
96 #\r
97 # Save PEM filename and close output file\r
98 #\r
99 args.PemFileName.append(Item.name)\r
100 Item.close()\r
101\r
102 #\r
103 # Generate private key and save it to output file in a PEM file format\r
104 #\r
a5f26fef 105 Process = subprocess.Popen('%s genrsa -out %s 2048' % (OpenSslCommand, Item.name), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
65ce860e 106 Process.communicate()\r
87d2afd0 107 if Process.returncode != 0:\r
72443dd2 108 print('ERROR: RSA 2048 key generation failed')\r
65ce860e 109 sys.exit(Process.returncode)\r
f7496d71 110\r
65ce860e
MK
111 #\r
112 # Check for input file argument\r
113 #\r
128d435f 114 if args.InputFile is not None:\r
65ce860e
MK
115 for Item in args.InputFile:\r
116 #\r
117 # Save PEM filename and close input file\r
118 #\r
119 args.PemFileName.append(Item.name)\r
120 Item.close()\r
121\r
d943b0c3 122 PublicKeyHash = bytearray()\r
65ce860e
MK
123 for Item in args.PemFileName:\r
124 #\r
125 # Extract public key from private key into STDOUT\r
126 #\r
a5f26fef 127 Process = subprocess.Popen('%s rsa -in %s -modulus -noout' % (OpenSslCommand, Item), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
d943b0c3 128 PublicKeyHexString = Process.communicate()[0].split(b'=')[1].strip()\r
87d2afd0 129 if Process.returncode != 0:\r
72443dd2 130 print('ERROR: Unable to extract public key from private key')\r
65ce860e 131 sys.exit(Process.returncode)\r
d943b0c3 132 PublicKey = bytearray()\r
65ce860e 133 for Index in range (0, len(PublicKeyHexString), 2):\r
d943b0c3 134 PublicKey = PublicKey + PublicKeyHexString[Index:Index + 2]\r
65ce860e
MK
135\r
136 #\r
137 # Generate SHA 256 hash of RSA 2048 bit public key into STDOUT\r
138 #\r
a5f26fef 139 Process = subprocess.Popen('%s dgst -sha256 -binary' % (OpenSslCommand), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
65ce860e
MK
140 Process.stdin.write (PublicKey)\r
141 PublicKeyHash = PublicKeyHash + Process.communicate()[0]\r
87d2afd0 142 if Process.returncode != 0:\r
72443dd2 143 print('ERROR: Unable to extract SHA 256 hash of public key')\r
65ce860e
MK
144 sys.exit(Process.returncode)\r
145\r
146 #\r
147 # Write SHA 256 hash of 2048 bit binary public key to public key hash file\r
148 #\r
149 try:\r
150 args.PublicKeyHashFile.write (PublicKeyHash)\r
151 args.PublicKeyHashFile.close ()\r
152 except:\r
153 pass\r
154\r
155 #\r
156 # Convert public key hash to a C structure string\r
157 #\r
158 PublicKeyHashC = '{'\r
159 for Item in PublicKeyHash:\r
d943b0c3 160 PublicKeyHashC = PublicKeyHashC + '0x%02x, ' % (Item)\r
65ce860e 161 PublicKeyHashC = PublicKeyHashC[:-2] + '}'\r
f7496d71 162\r
65ce860e
MK
163 #\r
164 # Write SHA 256 of 2048 bit binary public key to public key hash C structure file\r
165 #\r
166 try:\r
d943b0c3 167 args.PublicKeyHashCFile.write (bytes(PublicKeyHashC))\r
65ce860e
MK
168 args.PublicKeyHashCFile.close ()\r
169 except:\r
170 pass\r
f7496d71 171\r
65ce860e
MK
172 #\r
173 # If verbose is enabled display the public key in C structure format\r
174 #\r
175 if args.Verbose:\r
72443dd2 176 print('PublicKeySha256 = ' + PublicKeyHashC)\r