参考sha256t.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/sha.h> #include <openssl/evp.h> static char *s1 = "abc"; static char *s2 = "abcdbcde" "cdefdefg" "efghfghi" "ghijhijk" "ijkljklm" "klmnlmno" "mnopnopq"; static unsigned char app_b1[SHA256_DIGEST_LENGTH] = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }; static unsigned char app_b2[SHA256_DIGEST_LENGTH] = { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }; static unsigned char app_b3[SHA256_DIGEST_LENGTH] = { 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7, 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0 }; static char *pt(unsigned char *md) { int i; static char buf[80]; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) sprintf(&(buf[i * 2]), "%02x", md[i]); return (buf); } int main(int argc, char *argv[]) { unsigned char md[SHA256_DIGEST_LENGTH]; int i; EVP_MD_CTX evp; char *p; if (argc > 1) { printf("calculating SHA256 on '%s'\n", argv[1]); EVP_Digest(argv[1], strlen(argv[1]), md, NULL, EVP_sha256(), NULL); p = pt(md); printf("SHA256: %s\n", p); return 0; } printf("calculating SHA256 on '%s'\n", s1); EVP_Digest(s1, strlen(s1), md, NULL, EVP_sha256(), NULL); p = pt(md); printf("SHA256: %s\n", p); if (memcmp(md, app_b1, sizeof(app_b1))) { printf("\nTEST 1 of 3 failed.\n"); return 1; } else printf(".\n"); printf("calculating SHA256 on '%s'\n", s2); EVP_Digest(s2, strlen(s2), md, NULL, EVP_sha256(), NULL); p = pt(md); printf("SHA256: %s\n", p); if (memcmp(md, app_b2, sizeof(app_b2))) { printf("\nTEST 2 of 3 failed.\n"); return 1; } else printf(".\n"); printf("calculating SHA256 on 'a' * 1000000\n"); static unsigned char buf[160]; memset(buf, 'a', 160); EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); for (i = 0; i < 1000000; i += 160) EVP_DigestUpdate(&evp, buf, (1000000 - i) < 160 ? 1000000 - i : 160); EVP_DigestFinal_ex(&evp, md, NULL); EVP_MD_CTX_cleanup(&evp); p = pt(md); printf("SHA256: %s\n", p); if (memcmp(md, app_b3, sizeof(app_b3))) { printf("\nTEST 3 of 3 failed.\n"); return 1; } else printf(".\n"); return 0; }
运行结果
$ gcc -Wall -lcrypto sha256.c $ ./a.out calculating SHA256 on 'abc' SHA256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad . calculating SHA256 on 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq' SHA256: 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1 . calculating SHA256 on 'a' * 1000000 SHA256: cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 . $ ./a.out abc calculating SHA256 on 'abc' SHA256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad