From 11f1e5c1a6d064194ede5d0ef3500e1b0c8ec83c Mon Sep 17 00:00:00 2001 From: fangdingjun Date: Thu, 28 Jun 2018 09:53:38 +0800 Subject: [PATCH] add hash output length get function --- hash.go | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/hash.go b/hash.go index 0452593..849d358 100644 --- a/hash.go +++ b/hash.go @@ -10,25 +10,27 @@ import ( ) const ( - GNUTLS_MD5 = 2 - GNUTLS_SHA1 = 3 - GNUTLS_MD2 = 5 - GNUTLS_SHA256 = 6 - GNUTLS_SHA384 = 7 - GNUTLS_SHA512 = 8 - GNUTLS_SHA224 = 9 + GNUTLS_HASH_MD5 = 2 + GNUTLS_HASH_SHA1 = 3 + GNUTLS_HASH_MD2 = 5 + GNUTLS_HASH_SHA256 = 6 + GNUTLS_HASH_SHA384 = 7 + GNUTLS_HASH_SHA512 = 8 + GNUTLS_HASH_SHA224 = 9 ) // Hash hash struct type Hash struct { - hash C.gnutls_hash_hd_t - t int + hash C.gnutls_hash_hd_t + t int + hashLen C.int } // NewHash new hash struct func NewHash(t int) *Hash { h := C.new_hash(C.int(t)) - return &Hash{h, t} + hashOutLen := GetHashOutputLen(t) + return &Hash{h, t, C.int(hashOutLen)} } // Write write data to hash context @@ -51,14 +53,12 @@ func (h *Hash) Sum(buf []byte) []byte { h.Write(buf) } - hashOutLen := C.get_hash_len(C.int(h.t)) - - dstBuf := C.malloc(C.size_t(hashOutLen)) + dstBuf := C.malloc(C.size_t(h.hashLen)) defer C.free(dstBuf) C.gnutls_hash_output(h.hash, dstBuf) - gobuf := C.GoBytes(dstBuf, hashOutLen) + gobuf := C.GoBytes(dstBuf, h.hashLen) return gobuf } @@ -68,3 +68,9 @@ func (h *Hash) Close() error { C.gnutls_hash_deinit(h.hash, nil) return nil } + +// GetHashOutputLen get the hash algorithm output length +// example GNUTLS_MD5 is 16 +func GetHashOutputLen(t int) int { + return int(C.gnutls_hash_get_len(C.gnutls_digest_algorithm_t(t))) +}