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