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