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