tomcrypt/hash.c

94 lines
2.0 KiB
C
Raw Normal View History

2003-03-02 19:59:24 -05:00
#include "mycrypt.h"
int hash_memory(int hash, const unsigned char *data, unsigned long len, unsigned char *dst, unsigned long *outlen)
{
hash_state md;
2003-03-02 20:02:42 -05:00
int err;
2003-03-02 19:59:24 -05:00
_ARGCHK(data != NULL);
_ARGCHK(dst != NULL);
_ARGCHK(outlen != NULL);
2003-03-02 20:02:42 -05:00
if ((err = hash_is_valid(hash)) != CRYPT_OK) {
return err;
2003-03-02 19:59:24 -05:00
}
if (*outlen < hash_descriptor[hash].hashsize) {
return CRYPT_BUFFER_OVERFLOW;
}
*outlen = hash_descriptor[hash].hashsize;
hash_descriptor[hash].init(&md);
hash_descriptor[hash].process(&md, data, len);
hash_descriptor[hash].done(&md, dst);
return CRYPT_OK;
}
int hash_filehandle(int hash, FILE *in, unsigned char *dst, unsigned long *outlen)
{
#ifdef NO_FILE
2003-09-07 21:06:11 -04:00
return CRYPT_NOP;
2003-03-02 19:59:24 -05:00
#else
hash_state md;
unsigned char buf[512];
2003-03-02 20:02:42 -05:00
size_t x;
int err;
2003-03-02 19:59:24 -05:00
_ARGCHK(dst != NULL);
_ARGCHK(outlen != NULL);
_ARGCHK(in != NULL);
2003-03-02 20:02:42 -05:00
if ((err = hash_is_valid(hash)) != CRYPT_OK) {
return err;
2003-03-02 19:59:24 -05:00
}
if (*outlen < hash_descriptor[hash].hashsize) {
return CRYPT_BUFFER_OVERFLOW;
}
*outlen = hash_descriptor[hash].hashsize;
hash_descriptor[hash].init(&md);
do {
x = fread(buf, 1, sizeof(buf), in);
hash_descriptor[hash].process(&md, buf, x);
} while (x == sizeof(buf));
hash_descriptor[hash].done(&md, dst);
#ifdef CLEAN_STACK
zeromem(buf, sizeof(buf));
#endif
return CRYPT_OK;
#endif
}
int hash_file(int hash, const char *fname, unsigned char *dst, unsigned long *outlen)
{
#ifdef NO_FILE
2003-09-07 21:06:11 -04:00
return CRYPT_NOP;
2003-03-02 19:59:24 -05:00
#else
FILE *in;
2003-03-02 20:02:42 -05:00
int err;
2003-03-02 19:59:24 -05:00
_ARGCHK(fname != NULL);
_ARGCHK(dst != NULL);
_ARGCHK(outlen != NULL);
2003-03-02 20:02:42 -05:00
if ((err = hash_is_valid(hash)) != CRYPT_OK) {
return err;
2003-03-02 19:59:24 -05:00
}
in = fopen(fname, "rb");
if (in == NULL) {
return CRYPT_INVALID_ARG;
}
2003-03-02 20:02:42 -05:00
if ((err = hash_filehandle(hash, in, dst, outlen)) != CRYPT_OK) {
(void)fclose(in);
return err;
2003-03-02 19:59:24 -05:00
}
2003-03-02 20:02:42 -05:00
(void)fclose(in);
2003-03-02 19:59:24 -05:00
return CRYPT_OK;
#endif
}