summaryrefslogtreecommitdiffstats
path: root/src/sha.c
blob: 7b2126b55f9f770c6d0a94e8d14fb4828111ac3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* iksemel (XML parser for Jabber)
** Copyright (C) 2000-2003 Gurer Ozen
** This code is free software; you can redistribute it and/or
** modify it under the terms of GNU Lesser General Public License.
*/

#include <gcrypt.h>

#include "common.h"
#include "iksemel.h"

struct iksha_struct {
	gcry_md_hd_t c;
};

iksha *
iks_sha_new (void)
{
	iksha *sha;

	sha = iks_malloc (sizeof (iksha));
	if (!sha) return NULL;
	iks_sha_reset (sha);
	return sha;
}

void
iks_sha_reset (iksha *sha)
{
	memset (sha, 0, sizeof (iksha));
	gcry_md_open(&sha->c, GCRY_MD_SHA1, 0);
}

void
iks_sha_hash (iksha *sha, const unsigned char *data, size_t len, int finish)
{
	if (data && len != 0)
		gcry_md_write(sha->c, data, len);
	if (finish)
		gcry_md_final(sha->c);
}

void
iks_sha_print (iksha *sha, char *hash)
{
	unsigned char bin[20];
	int i;

	memcpy(bin, gcry_md_read(sha->c, 0), 20);

	for (i=0; i<20; i++)
	{
		sprintf (hash, "%02x", bin[i]);
		hash += 2;
	}
}

void
iks_sha_delete (iksha *sha)
{
	gcry_md_close(sha->c);
	iks_free (sha);
}

void
iks_sha (const char *data, char *hash)
{
	iksha *sha;

	sha = iks_sha_new ();
	iks_sha_hash (sha, (const unsigned char*)data, strlen (data), 1);
	iks_sha_print (sha, hash);
	iks_free (sha);
}