From f4be3682b9af6417ac8ec8629725350d4bc23bd7 Mon Sep 17 00:00:00 2001 From: dat nguyen Date: Fri, 15 Dec 2023 15:19:54 +0700 Subject: [PATCH] export fingerprint --- lib/Crypto/PublicKey/RSA.py | 12 ++++++++++++ lib/Crypto/PublicKey/RSA.pyi | 1 + lib/Crypto/SelfTest/PublicKey/test_import_RSA.py | 13 +++++++++++++ 3 files changed, 26 insertions(+) diff --git a/lib/Crypto/PublicKey/RSA.py b/lib/Crypto/PublicKey/RSA.py index f9beea4e0..b95f0f8c9 100644 --- a/lib/Crypto/PublicKey/RSA.py +++ b/lib/Crypto/PublicKey/RSA.py @@ -255,6 +255,18 @@ def __str__(self): key_type = "Public" return "%s RSA key at 0x%X" % (key_type, id(self)) + def export_fingerprint(self, hash_name = "MD5"): + bkey = self.exportKey(format='DER') + hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1", + "SHA224", "SHA256", "SHA384", "SHA512", + "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512") + + if hash_name not in hash_names: + return None + hashed = __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"]).new(bkey) + chunks = [hashed.hexdigest()[i:i+2] for i in range(0, len( hashed.hexdigest()), 2)] + return ":".join(chunks) + def export_key(self, format='PEM', passphrase=None, pkcs=1, protection=None, randfunc=None): """Export this RSA key. diff --git a/lib/Crypto/PublicKey/RSA.pyi b/lib/Crypto/PublicKey/RSA.pyi index dea63be62..4478da28b 100644 --- a/lib/Crypto/PublicKey/RSA.pyi +++ b/lib/Crypto/PublicKey/RSA.pyi @@ -38,6 +38,7 @@ class RsaKey(object): def __getstate__(self) -> None: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... + def export_fingerprint(self, hash_name = "MD5") -> str: ... def export_key(self, format: Optional[str]="PEM", passphrase: Optional[str]=None, pkcs: Optional[int]=1, protection: Optional[str]=None, randfunc: Optional[RNG]=None) -> bytes: ... diff --git a/lib/Crypto/SelfTest/PublicKey/test_import_RSA.py b/lib/Crypto/SelfTest/PublicKey/test_import_RSA.py index fa92fb0aa..4e1940bc5 100644 --- a/lib/Crypto/SelfTest/PublicKey/test_import_RSA.py +++ b/lib/Crypto/SelfTest/PublicKey/test_import_RSA.py @@ -419,6 +419,19 @@ def testExportKey15(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.export_key, 'DER', 'test', 1) + def testExportFingerPrint(self): + key = RSA.import_key(self.rsaKeyPEM) + self.assertEqual(key.export_fingerprint(), "4c:c8:ed:62:91:e3:4b:c9:9c:da:c9:2c:39:cf:3e:c2") + + def testExportFingerPrint2(self): + key = RSA.import_key(self.rsaPublicKeyDER) + self.assertEqual(key.export_fingerprint(), "40:d6:a0:30:74:e1:26:1a:73:df:f0:bb:2b:a9:3b:61") + + def testExportFingerPrint3(self): + key = RSA.import_key(self.rsaPublicKeyDER) + key1 = RSA.import_key(self.rsaPublicKeyPEM) + self.assertEqual(key.export_fingerprint(), key1.export_fingerprint()) + def test_import_key(self): """Verify that import_key is an alias to importKey""" key = RSA.import_key(self.rsaPublicKeyDER)