blob: 46d766cba9a62169ebe5ffea4facc08ce74df0ae [file] [log] [blame]
Giorgi Lekveishvili285ab622023-11-22 13:50:45 +04001# Copyright (C) 2019 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15from OpenSSL import crypto
16
17
18class MockSSLKeyPair:
19 def __init__(self, common_name, subject_alt_name):
20 self.common_name = common_name
21 self.subject_alt_name = subject_alt_name
22 self.cert = None
23 self.key = None
24
25 self._create_keypair()
26
27 def _create_keypair(self):
28 self.key = crypto.PKey()
29 self.key.generate_key(crypto.TYPE_RSA, 2048)
30
31 self.cert = crypto.X509()
32 self.cert.set_version(2)
33 self.cert.get_subject().O = "Gerrit"
34 self.cert.get_subject().CN = self.common_name
35 san = f"DNS:{self.subject_alt_name}"
36 self.cert.add_extensions(
37 [crypto.X509Extension(b"subjectAltName", False, san.encode())]
38 )
39 self.cert.gmtime_adj_notBefore(0)
40 self.cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
41 self.cert.set_issuer(self.cert.get_subject())
42 self.cert.set_pubkey(self.key)
43 self.cert.sign(self.key, "sha256")
44
45 def get_key(self):
46 return crypto.dump_privatekey(crypto.FILETYPE_PEM, self.key)
47
48 def get_cert(self):
49 return crypto.dump_certificate(crypto.FILETYPE_PEM, self.cert)