OpenSSL测试-SM3

  1. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务

  2. 使用OpenSSL的命令计算你的8位学号(数字)的摘要值(SM3),提交截图(5')

  3. 使用OpenSSL编程对计算"你的8位学号(数字)"SM3摘要值,提交代码和运行结果截图。(10’)

  4. 使用OpenSSL编程对计算内容为"所有同学的8位学号(文本)"的文件的SM3摘要值,提交代码和运行结果截图。(选做(10’))


2.代码:

#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
#include <stdio.h>

void handleErrors(void) {
    ERR_print_errors_fp(stderr);
    abort();
}

int main(void) {
    EVP_MD_CTX *mdctx;
    const EVP_MD *md;
    char message[] = "20211125";
    unsigned char md_value[EVP_MAX_MD_SIZE];
    unsigned int md_len, i;

    if((mdctx = EVP_MD_CTX_new()) == NULL)
        handleErrors();

    if((md = EVP_get_digestbyname("SM3")) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, md, NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, strlen(message)))
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, md_value, &md_len))
        handleErrors();

    EVP_MD_CTX_free(mdctx);

    printf("Digest is: ");
    for(i = 0; i < md_len; i++) printf("%02x", md_value[i]);
    printf("\n");

    return 0;
}

3.代码:

#include <openssl/evp.h>
#include <openssl/err.h>
#include <stdio.h>
#include <stdlib.h>

void handleErrors(void) {
    ERR_print_errors_fp(stderr);
    abort();
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <file to hash>\n", argv[0]);
        return 1;
    }

    FILE *file = fopen(argv[1], "rb");
    if (!file) {
        perror("Opening file failed");
        return 1;
    }

    EVP_MD_CTX *mdctx;
    const EVP_MD *md;
    unsigned char md_value[EVP_MAX_MD_SIZE];
    unsigned int md_len, i;
    unsigned char buffer[1024];
    int bytes;

    if ((mdctx = EVP_MD_CTX_new()) == NULL)
        handleErrors();

    if ((md = EVP_get_digestbyname("SM3")) == NULL)
        handleErrors();

    if (1 != EVP_DigestInit_ex(mdctx, md, NULL))
        handleErrors();

    while ((bytes = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        if (1 != EVP_DigestUpdate(mdctx, buffer, bytes))
            handleErrors();
    }

    if (1 != EVP_DigestFinal_ex(mdctx, md_value, &md_len))
        handleErrors();

    EVP_MD_CTX_free(mdctx);
    fclose(file);

    printf("SM3 Digest: ");
    for (i = 0; i < md_len; i++)
        printf("%02x", md_value[i]);
    printf("\n");

    return 0;
}

posted @ 2024-04-08 09:24  6666666mjz  阅读(53)  评论(0)    收藏  举报