openssl學習(一) 摘要

openssl學習(一)    摘要

說在前面的話:
  最近要作一個使用openssl生成證書請求以及證書的解析的工做,想着openssl的一些功能也是多多少少的用了幾年了,可是吧,對不少內容都是隻知其一;不知其二,不少編碼工做都是通了,好,就這樣吧.
  好在這個工做不是很着急,就趁着這個機會,好好學習一下openssl.
  把學習過程記錄下來,一是,加深本身的印象,二是,能夠和你們一塊兒討論.因此,若是發現有不對的地方,歡迎你們指正.
  今天就從最簡單的hash算法開始吧.
  對了,個人環境是ubuntu18.4,openssl-1.1.1算法

  數字摘要,哈希算法,散列函數,hash函數其實都是一個意思.就是將任意長度的數據,變成固定長度的短消息.不一樣的算法,生成的長度不同,以SHA爲例子.
  ubuntu

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

int main(void)
{
        unsigned char in[] = "abcdefghijklmnopqrstuvwxyz";
        unsigned char out[20] = {0};
        int in_len = strlen((const char *)in);
        int i;
        
        /* method 1,能夠屢次調用SHA1_Update,填充多組數據 */
        SHA_CTX sha_ctx;
        SHA1_Init(&sha_ctx);
        SHA1_Update(&sha_ctx, in, in_len);
        SHA1_Final(out, &sha_ctx);
        printf("SHA1 digest result :\n");
        for (i = 0; i < 20; i++)
                printf("%x ", out[i]);
        printf("\n");
        
        /* method 2 */
        SHA1(in, in_len, out);
        printf("SHA1 digest result :\n");
        for (i = 0; i < 20; i++)
                printf("%x ", out[i]);
        printf("\n");
        
        return 0;
}

SHA1計算的結果長度爲20.其餘的長度以下:
 #define SHA_DIGEST_LENGTH 20
 #define SHA224_DIGEST_LENGTH 28
 #define SHA256_DIGEST_LENGTH 32
 #define SHA384_DIGEST_LENGTH 48
 #define SHA512_DIGEST_LENGTH 64
 詳細能夠參看頭文件 openssl/sha.h.
經常使用的還有md算法,以及國產算法sm3,sm3將在之後的EVP中來學習.函數

相關文章
相關標籤/搜索