• openssl -- sha1函数进行消息摘要值计算 -- 代码


    #include <openssl/sha.h>
    #include <string.h>
    #include <stdio.h>

    void drump_hex(char * data, unsigned int len_data);

    int main()
    {
    SHA_CTX stx;
    unsigned char outmd[20]; //注意这里的字符个数是20

    FILE * file = NULL;
    int len = 0;
    char filename[32];
    char buffer[1024];
    memset(filename, 0, sizeof(filename));
    memset(buffer, 0, sizeof(buffer));

    char hello[] = "MY name is hello!!!";
    unsigned char SHA[SHA_DIGEST_LENGTH];
    unsigned char outmd2[20];
    int len_hello = 0;

    while(hello[len_hello])
    {
    len_hello++;
    }


    printf("Enter the file name, for SHA1 ");
    scanf("%s", filename);

    if((file = fopen(filename, "r")) == NULL)
    {
    printf("Can't open file ");
    return 0;
    }


    /*
    #include <openssl/sha.h>

    int SHA1_Init(SHA_CTX *c);
    int SHA1_Update(SHA_CTX *c, const void *data, size_t len);
    int SHA1_Final(unsigned char *md, SHA_CTX *c);

    unsigned char *SHA1(const unsigned char *d, size_t n,unsigned char *md); //返回一个指向哈希值的指针。

    SHA-1(安全哈希算法)是一个输出为160位的加密哈希函数。
    SHA1()计算在d处n个字节的SHA-1消息摘要,
    并将其放在md中(其中必须有SHA_DIGEST_LENGTH == 20字节的输出空间)。
    如果md为空,则将摘要放在一个静态数组中。

    如果消息没有完全存储在内存中,可以使用以下函数:
    SHA1_Init()初始化SHA_CTX结构。
    SHA1_Update()可以使用要散列的消息块(data地址的len个字节)重复调用。
    SHA1_Final()将消息摘要放在md中,其中必须有SHA_DIGEST_LENGTH == 20字节的输出空间,并擦除SHA_CTX。

    SHA1_Init()、SHA1_Update()和SHA1_Final()以及等效的SHA224、SHA256、SHA384和SHA512函数成功返回1,否则返回0。

    */
    SHA1_Init(&stx);
    while((len = fread(buffer, 1, 1024, file)) > 0)
    {
    printf("The original file is : %s ", buffer);
    SHA1_Update(&stx, buffer, len);
    memset(buffer, 0, sizeof(buffer));
    }
    SHA1_Final(outmd, &stx);

    printf("use SHA1_Init()... compute: ");
    drump_hex(outmd, SHA_DIGEST_LENGTH);

    printf(" ");


    printf("The original array is : %s ", hello);
    SHA1(hello, len_hello,outmd2);
    printf("SHA1 compute the hash data: ");
    drump_hex(outmd2, SHA_DIGEST_LENGTH);

    return 0;

    }

    void drump_hex(char * data, unsigned int len_data)
    {
    for(int i = 0; i < len_data; i++)
    {
    printf("%02x ", (unsigned char)data[i]);
    }
    printf(" ");
    }

    结果展示:

  • 相关阅读:
    Build 2016: 发布明天的云创新来服务今天的开发者
    微软在Build 2016开发者大会中发布 “认知服务”,牛津计划有正式名字啦!
    流行开源软件云上体验周 ——一种正确的云上开源软件体验姿势!
    让每个人都体验到来自云端的智能
    hdmap相关单词
    绝对误差和相对误差的定义
    高速公路之匝道
    hdmap相关
    虚拟参考站(VRS)
    matlab之结构体数组struct
  • 原文地址:https://www.cnblogs.com/ruigelwang/p/12750432.html
Copyright © 2020-2023  润新知