请按照之前博文的介绍配置openssl环境。代码如下:
#include <iostream> #include <openssl/sha.h> #include <openssl/crypto.h> // OPENSSL_cleanse #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") // 在本程序中, 可以注释掉这句 using namespace std; const char *orgStr = "hello"; //待哈希的串 // 打印前, 有必要转换 void printHash(unsigned char *md, int len) { int i = 0; for (i = 0; i < len; i++) { printf("%02x", md[i]); } printf("\n"); } void myHash1() { SHA_CTX c; unsigned char md[SHA_DIGEST_LENGTH]; SHA1((unsigned char *)orgStr, strlen(orgStr), md); printHash(md, SHA_DIGEST_LENGTH); SHA1_Init(&c); SHA1_Update(&c, orgStr, strlen(orgStr)); SHA1_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); printHash(md, SHA_DIGEST_LENGTH); } void myHash224() { SHA256_CTX c; unsigned char md[SHA224_DIGEST_LENGTH]; SHA224((unsigned char *)orgStr, strlen(orgStr), md); printHash(md, SHA224_DIGEST_LENGTH); SHA224_Init(&c); SHA224_Update(&c, orgStr, strlen(orgStr)); SHA224_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); printHash(md, SHA224_DIGEST_LENGTH); } void myHash256() { SHA256_CTX c; unsigned char md[SHA256_DIGEST_LENGTH]; SHA256((unsigned char *)orgStr, strlen(orgStr), md); printHash(md, SHA256_DIGEST_LENGTH); SHA256_Init(&c); SHA256_Update(&c, orgStr, strlen(orgStr)); SHA256_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); printHash(md, SHA256_DIGEST_LENGTH); } void myHash384() { SHA512_CTX c; unsigned char md[SHA384_DIGEST_LENGTH]; SHA384((unsigned char *)orgStr, strlen(orgStr), md); printHash(md, SHA384_DIGEST_LENGTH); SHA384_Init(&c); SHA384_Update(&c, orgStr, strlen(orgStr)); SHA384_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); printHash(md, SHA384_DIGEST_LENGTH); } void myHash512() { SHA512_CTX c; unsigned char md[SHA512_DIGEST_LENGTH]; SHA512((unsigned char *)orgStr, strlen(orgStr), md); printHash(md, SHA512_DIGEST_LENGTH); SHA512_Init(&c); SHA512_Update(&c, orgStr, strlen(orgStr)); SHA512_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); printHash(md, SHA512_DIGEST_LENGTH); } int main() { myHash1(); myHash224(); myHash256(); myHash384(); myHash512(); return 0; }与其他工具相比, 结果一致。