Skip to content

Commit 6d96baf

Browse files
committed
Ensure comment is always empty string on export
1 parent 6d14d91 commit 6d96baf

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/sshkey_tools/keys.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from cryptography.hazmat.primitives.asymmetric import rsa as _RSA
2727

2828
from . import exceptions as _EX
29-
from .utils import ensure_bytestring, ensure_string
29+
from .utils import ensure_bytestring, ensure_string, nullsafe_getattr
3030
from .utils import md5_fingerprint as _FP_MD5
3131
from .utils import sha256_fingerprint as _FP_SHA256
3232
from .utils import sha512_fingerprint as _FP_SHA512
@@ -129,12 +129,15 @@ def __init__(
129129
_SERIALIZATION.Encoding.OpenSSH,
130130
_SERIALIZATION.PublicFormat.OpenSSH,
131131
]
132+
133+
# Ensure comment is not None
134+
self.comment = nullsafe_getattr(self, "comment", "")
132135

133136
@classmethod
134137
def from_class(
135138
cls,
136139
key_class: PubkeyClasses,
137-
comment: Union[str, bytes] = None,
140+
comment: Union[str, bytes] = "",
138141
key_type: Union[str, bytes] = None,
139142
) -> "PublicKey":
140143
"""
@@ -266,7 +269,7 @@ def to_string(self, encoding: str = "utf-8") -> str:
266269
return " ".join(
267270
[
268271
ensure_string(self.serialize(), encoding),
269-
ensure_string(getattr(self, "comment", ""), encoding),
272+
ensure_string(nullsafe_getattr(self, "comment", ""), encoding),
270273
]
271274
)
272275

src/sshkey_tools/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,22 @@ def sha512_fingerprint(data: bytes, prefix: bool = True) -> str:
233233
)
234234

235235

236+
def nullsafe_getattr(obj, attr: str, default):
237+
"""
238+
Null-safe getattr, ensuring the result is not None.
239+
If the result is None, the default value is returned instead.
240+
241+
Args:
242+
obj: The object
243+
attr: The attribute to get
244+
default: The default value
245+
"""
246+
att = getattr(obj, attr, default)
247+
if att is None:
248+
att = default
249+
250+
return att
251+
236252
def join_dicts(*dicts) -> dict:
237253
"""
238254
Joins two or more dictionaries together.

0 commit comments

Comments
 (0)