zoukankan      html  css  js  c++  java
  • Generate sha256 with OpenSSL and C++

    By Adam Lamers

    https://stackoverflow.com/questions/2262386/generate-sha256-with-openssl-and-c

    void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
    {
        int i = 0;
    
        for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
        {
            sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
        }
    
        outputBuffer[64] = 0;
    }
    
    
    void sha256_string(char *string, char outputBuffer[65])
    {
        unsigned char hash[SHA256_DIGEST_LENGTH];
        SHA256_CTX sha256;
        SHA256_Init(&sha256);
        SHA256_Update(&sha256, string, strlen(string));
        SHA256_Final(hash, &sha256);
        int i = 0;
        for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
        {
            sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
        }
        outputBuffer[64] = 0;
    }
    
    int sha256_file(char *path, char outputBuffer[65])
    {
        FILE *file = fopen(path, "rb");
        if(!file) return -534;
    
        unsigned char hash[SHA256_DIGEST_LENGTH];
        SHA256_CTX sha256;
        SHA256_Init(&sha256);
        const int bufSize = 32768;
        unsigned char *buffer = malloc(bufSize);
        int bytesRead = 0;
        if(!buffer) return ENOMEM;
        while((bytesRead = fread(buffer, 1, bufSize, file)))
        {
            SHA256_Update(&sha256, buffer, bytesRead);
        }
        SHA256_Final(hash, &sha256);
    
        sha256_hash_string(hash, outputBuffer);
        fclose(file);
        free(buffer);
        return 0;
    }
  • 相关阅读:
    scala之旅-核心语言特性【多参数列表(柯里化)】(十二)
    scala之旅-核心语言特性【嵌套函数】(十一)
    集合+队列+锁
    JVM + GC 一遍过
    java agent测试
    actuator
    大话设计模式
    leetcode刷题之mysql精彩集锦
    Redis怎么保证与Mysql缓存一致性
    springcloud
  • 原文地址:https://www.cnblogs.com/liujx2019/p/14821939.html
Copyright © 2011-2022 走看看