使用openssl库EVP编程计算sha1值

参考sha1test.c

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <openssl/evp.h>
#include <openssl/sha.h>

static char *test[] = {
	"abc",
	"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
	NULL,
};

static char *ret[] = {
	"a9993e364706816aba3e25717850c26c9cd0d89d",
	"84983e441c3bd26ebaae4aa1f95129e5e54670f1",
};

static char *bigret = "34aa973cd4c4daa4f61eeb2bdbad27316534016f";

static char *pt(unsigned char *md)
{
	int i;
	static char buf[80];

	for (i = 0; i < SHA_DIGEST_LENGTH; i++)
		sprintf(&(buf[i * 2]), "%02x", md[i]);
	return (buf);
}

int main(void)
{
	int i, err = 0;
	char **P, **R;
	static unsigned char buf[1000];
	char *p, *r;
	EVP_MD_CTX c;
	unsigned char md[SHA_DIGEST_LENGTH];

	P = test;
	R = ret;
	i = 1;
	while (*P != NULL) {
		printf("calculating SHA1 on '%s'\n", *P);
		EVP_Digest(*P, strlen((char *)*P), md, NULL, EVP_sha1(), NULL);
		p = pt(md);
		printf("SHA1: %s\n", p);
		if (strcmp(p, (char *)*R) != 0) {
			printf("got %s instead of %s\n", p, *R);
			err++;
		} else
			printf("test %d ok\n", i);
		i++;
		R++;
		P++;
	}

	memset(buf, 'a', 1000);
	printf("calculating SHA1 on 'a * 1000' * 1000\n");
	EVP_MD_CTX_init(&c);
	EVP_DigestInit_ex(&c, EVP_sha1(), NULL);
	for (i = 0; i < 1000; i++)
		EVP_DigestUpdate(&c, buf, 1000);
	EVP_DigestFinal_ex(&c, md, NULL);
	EVP_MD_CTX_cleanup(&c);
	p = pt(md);
	printf("SHA1: %s\n", p);

	r = bigret;
	if (strcmp(p, r) != 0) {
		printf("got %s instead of %s\n", p, r);
		err++;
	} else
		printf("test 3 ok\n");

	EVP_MD_CTX_init(&c);
	EVP_DigestInit_ex(&c, EVP_sha1(), NULL);
	EVP_DigestUpdate(&c, "a", 1);
	EVP_DigestUpdate(&c, "b", 1);
	EVP_DigestUpdate(&c, "c", 1);
	EVP_DigestFinal_ex(&c, md, NULL);
	EVP_MD_CTX_cleanup(&c);
	p = pt(md);
	printf("SHA1: %s\n", p);

	return 0;
}


 

运行结果

 

$ gcc -Wall -lcrypto sha1.c

$ ./a.out 
calculating SHA1 on 'abc'
SHA1: a9993e364706816aba3e25717850c26c9cd0d89d
test 1 ok
calculating SHA1 on 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
SHA1: 84983e441c3bd26ebaae4aa1f95129e5e54670f1
test 2 ok
calculating SHA1 on 'a * 1000' * 1000
SHA1: 34aa973cd4c4daa4f61eeb2bdbad27316534016f
test 3 ok
SHA1: a9993e364706816aba3e25717850c26c9cd0d89d


 

你可能感兴趣的:(OpenSSL,SHA1)