Skip to content

Commit 9ce6c0d

Browse files
committed
crypto: Add type hints
Nothing to complicated here, other than working around mypy's dislike of changing variable types and inability to process 'if six.PY3' conditional blocks because it doesn't run the code. Part of blueprint add-emulated-virtual-tpm Change-Id: I805eaa8b6fb55ce9cbc8f6b8b777af48302ba2ba Signed-off-by: Stephen Finucane <[email protected]>
1 parent 7e4d8af commit 9ce6c0d

File tree

2 files changed

+32
-31
lines changed

2 files changed

+32
-31
lines changed

mypy-files.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
nova/crypto.py
12
nova/virt/driver.py
23
nova/virt/hardware.py
34
nova/virt/libvirt/__init__.py

nova/crypto.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121

2222
import base64
2323
import binascii
24+
import io
2425
import os
26+
import typing as ty
2527

2628
from cryptography.hazmat import backends
2729
from cryptography.hazmat.primitives.asymmetric import padding
@@ -31,7 +33,6 @@
3133
from oslo_concurrency import processutils
3234
from oslo_log import log as logging
3335
import paramiko
34-
import six
3536

3637
import nova.conf
3738
from nova import exception
@@ -44,7 +45,7 @@
4445
CONF = nova.conf.CONF
4546

4647

47-
def generate_fingerprint(public_key):
48+
def generate_fingerprint(public_key: str) -> str:
4849
try:
4950
pub_bytes = public_key.encode('utf-8')
5051
# Test that the given public_key string is a proper ssh key. The
@@ -56,58 +57,59 @@ def generate_fingerprint(public_key):
5657
digest = hashes.Hash(hashes.MD5(), backends.default_backend())
5758
digest.update(pub_data)
5859
md5hash = digest.finalize()
59-
raw_fp = binascii.hexlify(md5hash)
60-
if six.PY3:
61-
raw_fp = raw_fp.decode('ascii')
60+
raw_fp = binascii.hexlify(md5hash).decode('ascii')
6261
return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2]))
6362
except Exception:
6463
raise exception.InvalidKeypair(
6564
reason=_('failed to generate fingerprint'))
6665

6766

68-
def generate_x509_fingerprint(pem_key):
67+
def generate_x509_fingerprint(pem_key: ty.Union[bytes, str]) -> str:
6968
try:
70-
if isinstance(pem_key, six.text_type):
69+
if isinstance(pem_key, str):
7170
pem_key = pem_key.encode('utf-8')
7271
cert = x509.load_pem_x509_certificate(
7372
pem_key, backends.default_backend())
74-
raw_fp = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
75-
if six.PY3:
76-
raw_fp = raw_fp.decode('ascii')
73+
raw_fp = binascii.hexlify(
74+
cert.fingerprint(hashes.SHA1())
75+
).decode('ascii')
7776
return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2]))
7877
except (ValueError, TypeError, binascii.Error) as ex:
7978
raise exception.InvalidKeypair(
8079
reason=_('failed to generate X509 fingerprint. '
8180
'Error message: %s') % ex)
8281

8382

84-
def generate_key_pair(bits=2048):
83+
def generate_key_pair(bits: int = 2048) -> ty.Tuple[str, str, str]:
8584
key = paramiko.RSAKey.generate(bits)
86-
keyout = six.StringIO()
85+
keyout = io.StringIO()
8786
key.write_private_key(keyout)
8887
private_key = keyout.getvalue()
8988
public_key = '%s %s Generated-by-Nova' % (key.get_name(), key.get_base64())
9089
fingerprint = generate_fingerprint(public_key)
9190
return (private_key, public_key, fingerprint)
9291

9392

94-
def ssh_encrypt_text(ssh_public_key, text):
93+
def ssh_encrypt_text(ssh_public_key: str, text: ty.Union[str, bytes]) -> bytes:
9594
"""Encrypt text with an ssh public key.
9695
9796
If text is a Unicode string, encode it to UTF-8.
9897
"""
99-
if isinstance(text, six.text_type):
98+
if isinstance(text, str):
10099
text = text.encode('utf-8')
101100
try:
102101
pub_bytes = ssh_public_key.encode('utf-8')
103102
pub_key = serialization.load_ssh_public_key(
104103
pub_bytes, backends.default_backend())
105104
return pub_key.encrypt(text, padding.PKCS1v15())
106105
except Exception as exc:
107-
raise exception.EncryptionFailure(reason=six.text_type(exc))
106+
raise exception.EncryptionFailure(reason=str(exc))
108107

109108

110-
def generate_winrm_x509_cert(user_id, bits=2048):
109+
def generate_winrm_x509_cert(
110+
user_id: str,
111+
bits: int = 2048
112+
) -> ty.Tuple[str, str, str]:
111113
"""Generate a cert for passwordless auth for user in project."""
112114
subject = '/CN=%s' % user_id
113115
upn = '%s@localhost' % user_id
@@ -118,28 +120,26 @@ def generate_winrm_x509_cert(user_id, bits=2048):
118120

119121
_create_x509_openssl_config(conffile, upn)
120122

121-
(certificate, _err) = processutils.execute(
122-
'openssl', 'req', '-x509', '-nodes', '-days', '3650',
123-
'-config', conffile, '-newkey', 'rsa:%s' % bits,
124-
'-outform', 'PEM', '-keyout', keyfile, '-subj', subject,
125-
'-extensions', 'v3_req_client',
126-
binary=True)
123+
out, _ = processutils.execute(
124+
'openssl', 'req', '-x509', '-nodes', '-days', '3650',
125+
'-config', conffile, '-newkey', 'rsa:%s' % bits,
126+
'-outform', 'PEM', '-keyout', keyfile, '-subj', subject,
127+
'-extensions', 'v3_req_client',
128+
binary=True)
127129

128-
(out, _err) = processutils.execute('openssl', 'pkcs12', '-export',
129-
'-inkey', keyfile, '-password', 'pass:',
130-
process_input=certificate,
131-
binary=True)
130+
certificate = out.decode('utf-8')
132131

133-
private_key = base64.b64encode(out)
132+
out, _ = processutils.execute(
133+
'openssl', 'pkcs12', '-export', '-inkey', keyfile, '-password',
134+
'pass:', process_input=out, binary=True)
135+
136+
private_key = base64.b64encode(out).decode('ascii')
134137
fingerprint = generate_x509_fingerprint(certificate)
135-
if six.PY3:
136-
private_key = private_key.decode('ascii')
137-
certificate = certificate.decode('utf-8')
138138

139139
return (private_key, certificate, fingerprint)
140140

141141

142-
def _create_x509_openssl_config(conffile, upn):
142+
def _create_x509_openssl_config(conffile: str, upn: str):
143143
content = ("distinguished_name = req_distinguished_name\n"
144144
"[req_distinguished_name]\n"
145145
"[v3_req_client]\n"

0 commit comments

Comments
 (0)