实验一 密码引擎-1-OpenEuler-OpenSSL编译

发布时间 2023-04-12 08:04:40作者: 20201327刘谨铭
  1. 安装Ubuntu和OpenEuler虚拟机
  2. 下载最新的OpenSSL源码(1.1版本)
  3. 用自己的8位学号建立一个文件夹,cd 你的学号,用pwd获得绝对路径
  4. 参考https://www.cnblogs.com/rocedu/p/5087623.html先在Ubuntu中完成OpenSSL编译安装,然后在OpenEuler中重现
    ./config --prefix=..(学号目录的绝对路径)指定OpenSSL编译链接
  5. 提交 test_openssl.c 编译运行截图
  6. 加分项:在Windows中编译OpenSSL,记录编译过程,提交相关文档(推荐MarkDown格式)

Ubuntu

(一)环境

  • Ubuntu 22.04
  • OpenSSL 1.1.1t
    Ubuntu最新版本下载参见http://www.ubuntu.com/download/
    OpenSSL最新版本下载参见http://www.openssl.org/source/

OpenEuler


Window

安装Windows openssl

https://blog.csdn.net/wuliang20/article/details/121014060

配置环境变量


运行环境配置

在工具->编译选项->编译器->在连接器命令行加入以下命令:-llibcrypto,复选框需沟上

在工具->编译选项->目录->库 中添加:D:\北京电子科技学院\openeuler\OpenSSL-Win64\lib

在工具->编译选项->目录->C包含文件 中添加:D:\北京电子科技学院\openeuler\OpenSSL-Win64\include

在工具->编译选项->目录->C++包含文件 中添加:D:\北京电子科技学院\openeuler\OpenSSL-Win64\include

编译运行

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

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


OpenSSL 使用 base64 编码/解码

#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <string.h>
#include <iostream>

using namespace std;

char * base64Encode(const char *buffer, int length, bool newLine);
char * base64Decode(char *input, int length, bool newLine);

int main(int argc, char* argv[])
{
	bool newLine = false;
	string input = "Hello World!";

	char * encode = base64Encode(input.c_str(), input.length(), newLine);
	char * decode = base64Decode(encode, strlen(encode), newLine);

	cout << "Base64 Encoded : " << encode << endl;
	cout << "Base64 Decoded : " << decode << endl;

	cin.get();
	return 0;
}

// base64 编码
char * base64Encode(const char *buffer, int length, bool newLine)
{
	BIO *bmem = NULL;
	BIO *b64 = NULL;
	BUF_MEM *bptr;

	b64 = BIO_new(BIO_f_base64());
	if (!newLine) {
		BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	}
	bmem = BIO_new(BIO_s_mem());
	b64 = BIO_push(b64, bmem);
	BIO_write(b64, buffer, length);
	BIO_flush(b64);
	BIO_get_mem_ptr(b64, &bptr);
	BIO_set_close(b64, BIO_NOCLOSE);

	char *buff = (char *)malloc(bptr->length + 1);
	memcpy(buff, bptr->data, bptr->length);
	buff[bptr->length] = 0;
	BIO_free_all(b64);

	return buff;
}

// base64 解码
char * base64Decode(char *input, int length, bool newLine)
{
	BIO *b64 = NULL;
	BIO *bmem = NULL;
	char *buffer = (char *)malloc(length);
	memset(buffer, 0, length);
	b64 = BIO_new(BIO_f_base64());
	if (!newLine) {
		BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	}
	bmem = BIO_new_mem_buf(input, length);
	bmem = BIO_push(b64, bmem);
	BIO_read(bmem, buffer, length);
	BIO_free_all(bmem);

	return buffer;
}