如何使用openSSL和C ++加密一个块

时间:2015-09-23 07:51:48

标签: c++ openssl aes

我想使用AES-Rijndael的openSSL实现加密单个块。但是,一旦我使用openSSL函数,我就无法编译我的程序。

编译器说如下:

g++ aes.cpp -o application
/tmp/ccnmjLvT.o: In function `RunRijndael()':
aes.cpp:(.text+0x25c): undefined reference to `AES_set_encrypt_key'
aes.cpp:(.text+0x273): undefined reference to `AES_encrypt'
collect2: error: ld returned 1 exit status

我做错了什么?显然包含了库,因为AES_KEY似乎没有问题。但为什么我不能使用任何功能?

以下是一些示例代码来演示我的问题:

#include <cstdlib>
#include <iostream>
#include <string>

#include <openssl/aes.h>

using namespace std;

int BLOCKSIZE = 16;

//Hashes a string into an unsigned char.
unsigned char MyHash8(std::string data) {
    const int MOD_HASH = 255;
    unsigned char a = 1, b = 0;
    for (int index = 0; index < data.length(); ++index) {
        a = (a + data[index]) % MOD_HASH;
        b = (b + a) % MOD_HASH;
    }
    return (b << 4) | a;
}

//Hash-Function to generate an array of BLOCKSIZE length from given string.
unsigned char* GenerateBlock(std::string seed) {
    unsigned char* block = new unsigned char[BLOCKSIZE];
    for (int i = 0; i < BLOCKSIZE; i++) {
        block[i] = MyHash8(seed);
        seed += block[i] / 2 + 1;
    }
    return block;
}

/* 
 * This function generates a 16 byte secret and a 16 byte plaintext.
 * Then it creates the AES encryption key and with that it encrypts
 * the plaintext block.
 */
void RunRijndael() {
    unsigned char* userKey = GenerateBlock("test");
    int bits = BLOCKSIZE*8;
    AES_KEY* key;

    unsigned char* plaintextBlock = GenerateBlock("randomPlaintext");
    unsigned char* ciphertextBlock;


    /*
     * The compiler has problems with this part!
     * 
     * g++ aes.cpp -o application
     * /tmp/ccnmjLvT.o: In function `RunRijndael()':
     * aes.cpp:(.text+0x25c): undefined reference to `AES_set_encrypt_key'
     * aes.cpp:(.text+0x273): undefined reference to `AES_encrypt'
     * collect2: error: ld returned 1 exit status
     */
    AES_set_encrypt_key(userKey, bits, key);
    AES_encrypt(plaintextBlock, ciphertextBlock, key);
}

int main() {
    RunRijndael();
}

0 个答案:

没有答案