如何使用 OpenSSL 的 SHA256 函数
我正在编写一个程序来让自己熟悉 OpenSSL、libncurses 和 UDP 网络.我决定使用 OpenSSL 的 SHA256 来熟悉行业加密标准,但是我在使用它时遇到了问题.我已经将错误与 OpenSSL 与编译程序的链接隔离开来.我正在 64 位 Ubuntu 12.10 上工作.我已经安装了 libssl-dev 包.
I'm writing a program to get myself acquainted with OpenSSL, libncurses, and UDP networking. I decided to work with OpenSSL's SHA256 to become familiar with industry encryption standards, but I'm having issues with getting it working. I've isolated the error to the linking of OpenSSL with the compiled program. I'm working on Ubuntu 12.10, 64 bit. I have the package libssl-dev installed.
以 C++ main.cpp 为例:
Take, for instance, the C++ main.cpp:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
int main()
{
cout << sha256("test") << endl;
cout << sha256("test2") << endl;
return 0;
}
我正在使用 此处 的 SHA256() 函数作为OpenSSL 的 SHA256 功能的包装器.
I'm using the SHA256() function found here as a wrapper for OpenSSL's SHA256 functionality.
当我尝试使用以下 g++ 参数进行编译时,收到以下错误:
When I attempt to compile with the following g++ arguments, I receive the following error:
millinon@myhost:~/Programming/sha256$ g++ -lssl -lcrypto -o main main.cpp
/tmp/ccYqwPUC.o: In function `sha256(std::string)':
main.cpp:(.text+0x38): undefined reference to `SHA256_Init'
main.cpp:(.text+0x71): undefined reference to `SHA256_Update'
main.cpp:(.text+0x87): undefined reference to `SHA256_Final'
collect2: error: ld returned 1 exit status
因此,GCC 清楚地识别了 OpenSSL 定义的函数和类型,但 ld 未能找到 sha.h 中引用的函数符号.
So, GCC clearly recognizes OpenSSL's defined functions and types, but ld is failing to find the function symbols referred to in sha.h.
我是否需要手动指向特定的共享对象或目录?
Do I need to manually point to a specific shared object or directory?
谢谢!
推荐答案
您犯了一个非常常见的初学者错误...在构建时将链接的库放在命令行上的错误位置.
You make a very common beginners mistake... Putting the libraries you link with in the wrong place on the command line when you build.
依赖在命令行上是相反的,所以依赖于其他东西的东西实际上应该放在之前它依赖于命令行.
Dependencies are reversed on the command line, so something that depends on something else should actually be put before what it depends on on the command line.
在您的示例中,您有一个依赖于某些库集的源文件 main.cpp
,那么源文件应该在它所依赖的库之前:
In your example, you have a source file main.cpp
that depends on some set of libraries, then the source file should be before the libraries it depend on:
$ g++ -o main main.cpp -lssl -lcrypto
为了安全起见,始终将库放在最后,在命令行中列出的任何源文件或目标文件之后.
To be safe, always put libraries last, after any source or object files listed on the command line.
相关文章