Load file + encrypt/decrypt then read it

Hello,I have some issues when load a file and then wanna read the file with encrypt/decrypt method , w/out save it.
here my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <windows.h>

using namespace std;//encryption function to convert between cipher and original

void xor_encrypt(char *key, char *string, int n)
{
	int i;
	//length of password
	int keyLength = strlen(key);
	for (i = 0; i < n; i++)
	{
		//XOR Operation
		string[i] = string[i] ^ key[i%keyLength];
	}
}



char key[] = "thisiskey"; //password, this can be changed according to your wish but keep it large
//int choice; bool lock = false;
char LOCKEDFILENAME[] = "thisisfile.pak";


streampos size;
union
{
	long long int n;
	char ch[sizeof(long long int)];
} buffer; //temporary storage for processing encryption



//decrypt it.

DWORD WINAPI Decrypt(LPVOID lpParam)
{ //everything same as above
	
	ifstream locked;
	
	locked.open(LOCKEDFILENAME, ios::binary);
	

		if (locked.is_open())
		{
			locked.seekg(0, ios::end);
			size = locked.tellg();
			locked.seekg(0, ios::beg);

			while (locked.read(buffer.ch, sizeof(buffer)))
			{
				
				xor_encrypt(key, buffer.ch, sizeof(buffer));

				
			}

			
	}
	
	locked.close();
	return 0;
}

BOOL WINAPI DllMain(HMODULE hDll, DWORD dwReason, LPVOID lpReserved)
{
	DisableThreadLibraryCalls(hDll);
	if (dwReason == DLL_PROCESS_ATTACH) {
		CreateThread(0, 0, Decrypt, 0, 0, 0);
		
	}
	return TRUE;
}

i hope someone help me to fix this code, thanks before ^_^ cmiiw
Last edited on
closed account (48bpfSEw)
your buffer declaration is wrong imho

1
2
3
4
5
union
{
	long long int n;
	char ch[sizeof(long long int)];
} buffer; //temporary storage for processing encryption 



ch has a size of a size of "long long int" ... about 4 byte + 4 byte

and you try to read in this small buffer and overwrite your memory!

@Necip
so what i need to resolve thats
closed account (48bpfSEw)
think about malloc and delete

http://stackoverflow.com/questions/3115564/allocating-char-array-using-malloc


allocate the buffer
and free it after use.
Topic archived. No new replies allowed.