当前环境
- 系统:win10
- 开发工具: qt-creator
- 编译工具: qmake
- openssl版本:Win64 OpenSSL v1.1.1i
安装OpenSSL有两种方法,第一种为下载OpenSSL源代码并由自己编译后使用;第二种为下载已编译好的安装包,安装后直接可以使用。因第一种方法十分繁琐,需要安装Ruby进行编译,同时编译过程中可能产生各种各种的问题,因此在此采用第二种方法
开始
1、从http://slproweb.com/products/Win32OpenSSL.html下载已经编译好的包含 lib 和 include 文件的安装包
- 此处有Win32和Win64可选,这里的位数指的是你调用OpenSSL开发出来的软件的位数版本,而不是你计算机的位数。
- 开发32位软件选择Win32,64位选择Win64,如果同时需要开发32位和64位的则下载两个
- 注意,不要下载 light 版本,因为 light 版本不带 lib 和 include。如下图:
2、下载完后打开安装,选择安装位置,64位和32位不要安装在同一个目录下。我这里安装到C:\Users\oceanstar\source\others\OpenSSL-Win64
3、选择把dll复制到OpenSSL目录下(主要是为了以后好找,如果选择复制到Windows系统目录下,天知道复制到哪里去了。。。)
OpenSSL 就这样安装完毕了,如果你按网上自己编译的方法去自己编译,恐怕要耗上你至少半天的时间。我们来看看他的目录结构。
- bin:包含了测试程序、存储证书和密钥的文件(*.pem)。
- include:包含了所有的头文件(例如:aes.h、md5.h)。
- lib:包含了所有的库文件(例如:libeay32.lib、ssleay32.lib)。
使用
1、创建一个工程
2、在openssl_test.pro
最下面添加:
INCLUDEPATH += C:\Users\oceanstar\source\others\OpenSSL-Win64\include
LIBS += C:\Users\oceanstar\source\others\OpenSSL-Win64\lib\libssl.lib \
C:\Users\oceanstar\source\others\OpenSSL-Win64\lib\libcrypto.lib
3、修改main.cpp
#include <QCoreApplication>
#include <openssl/ssl.h>
#include <QDebug>
std::string sha256(const std::string str)
{
char buf[2];
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
std::string newString = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(buf,"%02x",hash[i]);
newString = newString + buf;
}
return newString;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::string str = "Hello World";
qDebug() << QString::fromStdString(sha256(str));
return a.exec();
}
4、我们编译运行它
发现报错:
说明:类似exited with code -1073741515
这样的错误都是因为缺少某些dll文件
解决:将OpenSSL-Win64\bin目录下缺失的dll复制到项目的debug目录下
重新运行它,即可解决:
参考:
OpenSSL在QT中的使用