crypto: add ability to query hash digest len
authorDaniel P. Berrange <berrange@redhat.com>
Fri, 23 Oct 2015 15:14:50 +0000 (16:14 +0100)
committerDaniel P. Berrange <berrange@redhat.com>
Wed, 23 Dec 2015 11:02:20 +0000 (11:02 +0000)
Add a qcrypto_hash_digest_len() method which allows querying of
the raw digest size for a given hash algorithm.

Reviewed-by: Eric Blake <eblake@redhat.com>
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
crypto/hash.c
include/crypto/hash.h
tests/test-crypto-hash.c

index 81e74de8681245f4ae77c01b47d2fe9a7251ba5f..5a47b90ec0c3e94153b1ac0c78d7ffcf7a8eb03f 100644 (file)
@@ -30,6 +30,12 @@ static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG_LAST] = {
     [QCRYPTO_HASH_ALG_SHA256] = GNUTLS_DIG_SHA256,
 };
 
+static size_t qcrypto_hash_alg_size[QCRYPTO_HASH_ALG_LAST] = {
+    [QCRYPTO_HASH_ALG_MD5] = 16,
+    [QCRYPTO_HASH_ALG_SHA1] = 20,
+    [QCRYPTO_HASH_ALG_SHA256] = 32,
+};
+
 gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)
 {
     if (alg < G_N_ELEMENTS(qcrypto_hash_alg_map)) {
@@ -38,6 +44,15 @@ gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)
     return false;
 }
 
+size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg)
+{
+    if (alg >= G_N_ELEMENTS(qcrypto_hash_alg_size)) {
+        return 0;
+    }
+    return qcrypto_hash_alg_size[alg];
+}
+
+
 int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
                         const struct iovec *iov,
                         size_t niov,
index b5acbf638c3e165a60e877f9a8bba9250ec06699..3d1812442f8d0173e4213a4e23819623da61b750 100644 (file)
@@ -44,6 +44,17 @@ typedef enum {
  */
 gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg);
 
+
+/**
+ * qcrypto_hash_digest_len:
+ * @alg: the hash algorithm
+ *
+ * Determine the size of the hash digest in bytes
+ *
+ * Returns: the digest length in bytes
+ */
+size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg);
+
 /**
  * qcrypto_hash_bytesv:
  * @alg: the hash algorithm
index 911437e60d6811af421d7fe6da2b942b0498eccd..3ec31dde7bb422bbac3b691519aed50745403c06 100644 (file)
@@ -163,6 +163,11 @@ static void test_hash_digest(void)
     for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
         int ret;
         char *digest;
+        size_t digestsize;
+
+        digestsize = qcrypto_hash_digest_len(i);
+
+        g_assert_cmpint(digestsize * 2, ==, strlen(expected_outputs[i]));
 
         ret = qcrypto_hash_digest(i,
                                   INPUT_TEXT,