How to use OpenSSL SHA256 features

I am writing a program to get acquainted with OpenSSL, libncurses, and UDP networks. I decided to work with OpenSSL SHA256 to familiarize myself with industry-standard encryption standards, but I have problems with its operation. I highlighted an error for linking OpenSSL with a compiled program. I am working on Ubuntu 12.10, 64 bit. I have installed the libssl-dev package.

Take, for example, 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; } 

I am using the SHA256 () function found here as a wrapper for the OpenSSL SHA256 functions.

When I try to compile the following g ++ arguments, I get 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 

So, GCC clearly recognizes certain functions and types of OpenSSL, but ld does not find the functional characters mentioned in sha.h.

Do I need to manually specify a specific shared object or directory?

Thank!

+10
c ++ gcc openssl sha256
Dec 09
source share
2 answers

You make a very common beginner mistake ... Put the libraries you link to in the wrong place on the command line when creating.

Dependencies are canceled on the command line, so something that depends on something else should actually be put before what depends on the command line.

In your example, you have the main.cpp source file, which depends on some set of libraries, then the source file must be before the libraries depend on it:

 $ g++ -o main main.cpp -lssl -lcrypto 

To be safe, always leave the libraries last after any source or object files listed on the command line.

+20
Dec 09
source share

This works fine on my system, but you can try:

 extern "C" { #include <openssl/sha.h> } 

which tells g ++ that all materials in openssl / sha.h are declared as "C".

By the way, how old is your OpenSSL?

0
Dec 09 '12 at 4:00
source share



All Articles