-3
\$\begingroup\$

I created function for calculating fingerprint from a public key

fun calculateFingerprint(publicKey: String): String {
  return MessageDigest.getInstance("MD5")
    .digest(Base64.decode(publicKey.split(" ")[1]))
    .joinToString(separator = ":") { digest -> "%02x".format(digest) }
}
\$\endgroup\$
2
  • 7
    \$\begingroup\$ Welcome to Code Review@SE. Without some context, do you expect anything beyond looks good? See How to get the best value out of Code Review & co. \$\endgroup\$
    – greybeard
    Feb 23, 2022 at 9:36
  • 2
    \$\begingroup\$ Is MD5 required for interoperability with some other system? Or did you choose it? \$\endgroup\$ Feb 23, 2022 at 10:43

1 Answer 1

1
\$\begingroup\$

A fingerprint over a public key is generally not calculated over a string, it is calculated over the modulus. The reason for that is that the fingerprint of the public key is then the same as the one over the private key, so if they match you can be certain that they form a key pair.

For certificates, the main carriers of a public keys, the certificate fingerprint is calculated over the DER encoding of the entire certificate, so excluding any base64 encoding. If you are talking about that then you should name your string certificate, not public key. And in that case you'd probably get the PEM encoding, which doesn't just contain the base64 but also a header and footer line.

Moreover, generally SHA-1 is used to calculate fingerprints. That's not the best algorithm anymore for this kind of thing, but I suppose it still might work. Let's say it is traditional. However, in the end you may need collision resistance, and although SHA-1 is slightly broken against that, MD5 is much much worse.

Generally fingerprints are displayed in hexadecimals indeed. However, your function signature just reads calculateFingerprint(publicKey: String): String. That means that any user doesn't get any indication how these should be encoded.


One thing that is not a good idea either is to split the public key over a space character. What space is that and why would you use index 1 on the resulting array? Have you ever heard of the principle of "least surprise"? What data is in that base64 encoding. Why not assign that data to a variable first that at least identifies the data element by name? Why not create a constant for 1 that does the same?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.