openssl——实验一

openssl实践——实验一
20201303张奕博

0. 安装Ubuntu和OpenEuler虚拟机
1. 下载最新的OpenSSL源码(1.1版本)
2. 用自己的8位学号建立一个文件夹,cd 你的学号,用pwd获得绝对路径
3. 参考https://www.cnblogs.com/rocedu/p/5087623.html先在Ubuntu中完成OpenSSL编译安装,然后在OpenEuler中重现
        ./config  --prefix=..(学号目录的绝对路径)指定OpenSSL编译链接
4. 提交 test_openssl.c 编译运行截图        

1.新建文件夹

2.安装openssl 并且检查是否可行

3.实践代码(test_openssl.c)

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

int main(){
	
    OpenSSL_add_all_algorithms();
	
    return 0;
}

加分题:
1.下载openssl在windows上

2.配置环境


3.测试代码

#include <openssl/pem.h>
#include <stdio.h>
using namespace std;

int openssl_base64_encode(const unsigned char* in, int inlen, char* out, int* outlen, bool newline)
{
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bmem = BIO_new(BIO_s_mem());
    if (!b64 || !bmem) {
        fprintf(stderr, "fail to BIO_new\n");
        return -1;
    }

    b64 = BIO_push(b64, bmem);
    if (!newline)
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // ignore newlines, write everything in one line

    *outlen = BIO_write(b64, in, inlen);
    if (*outlen <= 0 || *outlen != inlen) {
        fprintf(stderr, "fail to BIO_write\n");
        return -1;
    }

    BIO_flush(b64);
    BUF_MEM* buf = nullptr;
    BIO_get_mem_ptr(b64, &buf);
    *outlen = buf->length;
    memcpy(out, buf->data, *outlen);
    BIO_free_all(b64);
    return 0;
}

int openssl_base64_decode(const char* in, int inlen, unsigned char* out, int* outlen, bool newline)
{
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bmem = BIO_new_mem_buf(in, inlen);
    if (!b64 || !bmem) {
        fprintf(stderr, "fail to BIO_new\n");
        return -1;
    }

    b64 = BIO_push(b64, bmem);
    if (!newline)
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // ignore newlines, write everything in one line

    *outlen = BIO_read(b64, out, inlen);
    if (*outlen <= 0) {
        fprintf(stderr, "fail to BIO_read\n");
        return -1;
    }

    BIO_free_all(b64);
    return 0;
}

void base64_test()
{
    char jwtHeader[] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
    printf("jwt header origin:%s\n", jwtHeader);
    unsigned char jwtDecode[256] = {0};
    int jwtDecodeLen = 0;
    openssl_base64_decode(jwtHeader, strlen(jwtHeader), jwtDecode, &jwtDecodeLen, false);
    jwtDecode[jwtDecodeLen] = '\0';
    printf("jwt header decode:%s\n", jwtDecode);

    char jwtEncode[256] = {0};
    int jwtEncodeLen = 0;
    openssl_base64_encode(jwtDecode, strlen((char*)jwtDecode), jwtEncode, &jwtEncodeLen, false);
    jwtEncode[jwtEncodeLen] = '\0';
    printf("jwt header encode:%s\n", jwtEncode);
}

int main()
{
    base64_test();
    return 0;
}
  

posted @ 2023-03-21 16:07  20201303张奕博  阅读(56)  评论(0编辑  收藏  举报