Could someone help me. I don't know why i get a stack corruption . Here is my program:

#include<iostream>
#include <fstream>
#include<conio.h>
#include <string>
#include "aes.h"
using namespace std;

int main(int argc, char **argv)
{
unsigned char key32[32];
unsigned char iv[16];
unsigned char* inbuf=new unsigned char[128];
unsigned char** intext=new unsigned char*[16];
unsigned char outbuf[128];

//memset(inbuf, 0, sizeof(inbuf));
cout<<"enter text:";
cin>>inbuf;
int lenght=strlen(reinterpret_cast<char*>(inbuf));

ifstream keyfile("file.key");
if(keyfile.is_open())
	{
		keyfile>>key32;
		cout<<key32<<endl;
	}
cout<<key32<<endl;
ifstream ivfile("file.iv");
if(ivfile.is_open())
	{
		ivfile>>iv;
		cout<<iv<<endl;
	}
ofstream criptfile("file.out");
memset(outbuf, 0, sizeof(outbuf));
AES_KEY aeskey;
AES_set_encrypt_key(key32, 32*8, &aeskey);
int n=lenght/16;
cout<<lenght<<endl;
cout<<n<<endl;
int rest=lenght%16;
if(rest!=0) n++;
for (int i = 0; i < n; i++)
	intext[i]=new unsigned char[n]; 
for(int e=0;e<n;e++)
	for(int d=0;d<16;d++)	
		intext[e][d]=0;
int l=0;
int m=0;
for(int j=0;j<lenght;j++)
{
	intext[l][m]=inbuf[j];	
	m++;
	if(m==16)
	{
		l++;
		m=0;
	}
	
}
for(int k=0;k<n;k++)
{
AES_cbc_encrypt(intext[k], outbuf, 16, &aeskey, iv, AES_ENCRYPT);
	if(criptfile.is_open())
	{
		criptfile<<outbuf;
		cout<<outbuf;
	}
}
keyfile.close();
ivfile.close();
criptfile.close();
//getch();
}

The error that i get is: stack around the variable 'iv' was corrupted.

Which line?

the compiler shows it at the last line , line 74 . I don't know why this happens.

Try a breakpoint.

the actual corruption happens at line 63:

AES_cbc_encrypt(intext[k], outbuf, 16, &aeskey, iv, AES_ENCRYPT);

. Why this happens i don't know.

This will screw up if your message length is less than 16, n becomes zero (or 1) in which case you allocate a small square array, but d ALWAYS goes to 16. This will corrupt your stack pretty quickly. Look at your algorithm around 46 & 47. You might try something like if length < 16 length = 16 above and pad your message to 16.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.