变量周围的堆栈已损坏

时间:2014-09-11 18:14:32

标签: c++ c openssl aes stack-corruption

我有以下程序,其中我使用AES_CBC加密和解密给定文本,密钥长度为256位。我想知道为什么当plaintextciphertextchecktext不是全局变量时,我在标题中出现错误,并且当它们正常时可以正常工作。谢谢!

#include <stdio.h>
#include <openssl\aes.h>
#include <openssl\rand.h>
#include <conio.h>
#include <openssl\des.h>

#define BIG_TEST_SIZE 1024

char plaintext[BIG_TEST_SIZE];
char ciphertext[BIG_TEST_SIZE];
char checktext[BIG_TEST_SIZE];

AES_KEY key;
char rkey[32+1];

static void hexdump(FILE *f,const char *title,const unsigned char *s,int l)
{
        int n=0;

        fprintf(f,"%s",title);
        for( ; n < l ; ++n)
        {
                if((n%16) == 0)
                        fprintf(f,"\n%04x",n);
                fprintf(f," %02x",s[n]);
        }
        fprintf(f,"\n");
}

int main(int argc, char* argv[])
{
    //char plaintext[BIG_TEST_SIZE];
    //char ciphertext[BIG_TEST_SIZE];
    //char checktext[BIG_TEST_SIZE];    

    char saved_iv[32+1];
        int err = 0;

        RAND_pseudo_bytes((unsigned char*)rkey, sizeof rkey);
        unsigned char iv[32+1]="01234567890123456789012345678901";

        memcpy(saved_iv, iv, sizeof saved_iv);

        strcpy((char*)plaintext,"aaa");

        const size_t encslength = ((strlen(plaintext) + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
        // Straight encrypt

        AES_set_encrypt_key((unsigned char*)rkey, 256, &key);
        hexdump(stdout, "plaintext", (unsigned char*)plaintext, strlen(plaintext));

        AES_cbc_encrypt((unsigned char*)plaintext, (unsigned char*)ciphertext, encslength, &key, (unsigned char*)iv,AES_ENCRYPT);
        hexdump(stdout, "ciphertext", (unsigned char*)ciphertext, strlen(plaintext));

        // Straight decrypt

        AES_set_decrypt_key((unsigned char*)rkey, 256, &key);
        memcpy(iv, saved_iv, sizeof iv);

        AES_cbc_encrypt((unsigned char*)ciphertext, (unsigned char*)checktext, encslength, &key, (unsigned char*)iv,AES_DECRYPT);
        hexdump(stdout, "checktext", (unsigned char*)checktext, strlen(plaintext));


        getch();
}

1 个答案:

答案 0 :(得分:1)

全局和静态变量初始化为零,而局部变量不是。 因此,当您在本地定义明文密文 checktext 时,请使用memset将其初始化为零。 你的字符串应该是空终止,但在你的情况下它不是。 密文 checktext 未终止。由于 strcpy 调用,明文变为空终止。