From a6606e393c25f582805611aee652a4597e2cde31 Mon Sep 17 00:00:00 2001 From: Paul Schaub Date: Tue, 30 Apr 2024 12:34:21 +0200 Subject: [PATCH] Add HashUtils helper for looking up salt sizes for digest algorithms --- .../java/org/bouncycastle/bcpg/HashUtils.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java diff --git a/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java b/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java new file mode 100644 index 0000000000..b4576391b6 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java @@ -0,0 +1,53 @@ +package org.bouncycastle.bcpg; + +public class HashUtils +{ + + /** + * Return the length of the salt per hash algorithm, used in OpenPGP v6 signatures. + * + * @see + * Salt Size declarations + * @param hashAlgorithm hash algorithm tag + * @return size of the salt for the given hash algorithm in bytes + */ + public static int getV6SignatureSaltSizeInBytes(int hashAlgorithm) + { + switch (hashAlgorithm) + { + case HashAlgorithmTags.SHA256: + case HashAlgorithmTags.SHA224: + case HashAlgorithmTags.SHA3_256: + case HashAlgorithmTags.SHA3_256_OLD: + return 16; + case HashAlgorithmTags.SHA384: + return 24; + case HashAlgorithmTags.SHA512: + case HashAlgorithmTags.SHA3_512: + case HashAlgorithmTags.SHA3_512_OLD: + return 32; + default: + throw new IllegalArgumentException("Salt size not specified for Hash Algorithm with ID " + hashAlgorithm); + } + } + + /** + * Return true, if the encountered saltLength matches the value the specification gives for the hashAlgorithm. + * + * @param hashAlgorithm hash algorithm tag + * @param saltSize encountered salt size + * @return true if the encountered size matches the spec + * @implNote LibrePGP allows for zero-length signature salt values, so this method only works for IETF OpenPGP v6. + */ + public boolean saltSizeMatchesSpec(int hashAlgorithm, int saltSize) + { + try + { + return saltSize == getV6SignatureSaltSizeInBytes(hashAlgorithm); + } + catch (IllegalArgumentException e) // Unknown algorithm or salt size is not specified for the hash algo + { + return false; + } + } +}