Slightly different SHA256 on windows and linux - c++

The code below generates SHA256 hash on Windows. As you can see it produces the hash from text "doublecheck" (5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=)
I've created the code in the linux which should produce same hash, but it is different. (5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3O/enx3tzCun78sgwQIOK6fv1T6eLc=)
Could anybody help me to fix any of those codes to get the same hashes?
Windows code:
#include "stdafx.h"
#include "Hash2.h"
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
DWORD BufSize;
#define BUF_SIZE 256
TCHAR Buf[BUF_SIZE];
CStringA BinaryToBase64(__in const byte * pbBinary, __in DWORD cbBinary)
{
ATLASSERT(pbBinary != NULL);
if (pbBinary == NULL)
AtlThrow(E_POINTER);
ATLASSERT(cbBinary != 0);
if (cbBinary == 0)
AtlThrow(E_INVALIDARG);
DWORD cchBase64;
if (!CryptBinaryToStringA(pbBinary, cbBinary, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &cchBase64))
{
AtlThrowLastWin32();
}
CStringA strBase64;
LPSTR pszBase64 = strBase64.GetBuffer(cchBase64);
ATLASSERT(pszBase64 != NULL);
if (!CryptBinaryToStringA(pbBinary, cbBinary, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, pszBase64, &cchBase64))
AtlThrowLastWin32();
strBase64.ReleaseBuffer();
return strBase64;
}
// creates sha256 hash from string
LPCSTR CreateHash(LPCSTR tohash)
{
HCRYPTPROV hProv;
HCRYPTHASH hash;
if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if (CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hash))
{
int sz = strlen(tohash);
if (CryptHashData(hash, (BYTE *)tohash, sz, 0))
{
ZeroMemory(&Buf, sizeof(Buf));
BufSize = sizeof(Buf);
if (!CryptGetHashParam(hash, HP_HASHVAL, (BYTE *)&Buf, &BufSize, 0))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
if (!CryptDestroyHash(hash))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
if (!CryptReleaseContext(hProv, 0))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
CStringA stemp = BinaryToBase64(reinterpret_cast<BYTE *>(Buf), BufSize).Trim();
int sizeOfString = (stemp.GetLength() + 1);
LPSTR retVal = new char[sizeOfString];
strcpy_s(retVal, sizeOfString, stemp);
return retVal;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
LPCSTR text = "doublecheck";
LPCSTR hash = CreateHash(text);
printf("\"%s\" hashed = %s", text, hash);
//output: "doublecheck" hashed = 5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=
getchar();
}
Linux code:
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
int Base64Encode(const char* message, char** buffer) { //Encodes a string to base64
BIO *bio, *b64;
FILE* stream;
int encodedSize = 4*ceil((double)strlen(message)/3);
*buffer = (char *)malloc(encodedSize+1);
stream = fmemopen(*buffer, encodedSize+1, "w");
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stream, BIO_NOCLOSE);
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Ignore newlines - write everything in one line
// edit: bad code BIO_write(bio, message, strlen(message));
BIO_write(bio, message, SHA256_DIGEST_LENGTH); // edit: correction
BIO_flush(bio);
BIO_free_all(bio);
fclose(stream);
return (0); //success
}
int main() {
unsigned char digest[SHA256_DIGEST_LENGTH];
const char* string = "doublecheck";
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, string, strlen(string));
SHA256_Final(digest, &ctx);
printf("SHA256 digest: %s\n", digest);
char* base64EncodeOutput;
Base64Encode((char*)digest, &base64EncodeOutput);
printf("Output (base64): %s\n", base64EncodeOutput);
// now the output here is: 5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=
return 0;
}

Related

Encrypt file with AES in python and Decrypt in C++ Windows

I wrote this code to encrypt a file in python with AES and now I send this file over HTTP to a client in C++ using Windows OS. And I want to decrypt this file on the C++ client, but I haven't found any libraries/usefull code to help me with this manner.
Here is the code for python:
def derive_key_and_iv(password, salt, key_length, iv_length):
d = d_i = b''
while len(d) < key_length + iv_length:
d_i = md5(d_i + str.encode(password) + salt).digest()
d += d_i
return d[:key_length], d[key_length:key_length + iv_length]
def encrypt(in_file, out_file, password, key_length=32):
bs = AES.block_size # 16 bytes
salt = urandom(bs)
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
out_file.write(salt)
finished = False
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0: #final block
padding_length = (bs - len(chunk) % bs) or bs
chunk += str.encode(padding_length * chr(padding_length))
finished = True
out_file.write(cipher.encrypt(chunk))
password = 'ABCDE' # some password
with open("some_file.bin", "rb") as in_file, open("enc_some_file.enc", "wb") as out_file:
encrypt(in_file, out_file, password)
Update:
I am updating this question regarding my try with WinCrypt. I am trying to compile from VS CODE using MSYS64 g++ compiler on Windows. Here is the code that I am trying to run. I also have some additional libraries to help me with the client-server part, such as libcurlpp and libcurl.
#include <string>
#include <sstream>
#include <conio.h>
#include <iostream>
#include <fstream>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <wincrypt.h>
#include <windows.h>
#define AES_KEY_SIZE 32
#define IN_CHUNK_SIZE (AES_KEY_SIZE * 10) // a buffer must be a multiple of the key size
#define OUT_CHUNK_SIZE (IN_CHUNK_SIZE * 2) // an output buffer (for encryption) must be twice as big
using namespace std;
string host = ""; #some host
int main(void)
{
curlpp::Easy req;
req.setOpt(new curlpp::options::Url(host));
ofstream myfile;
myfile.open("enc_calc.enc", ios::out | ios::binary);
myfile << req;
myfile.close();
getch();
wchar_t *in_file = (wchar_t *)"enc_calc.enc";
wchar_t *out_file = (wchar_t *)"calc.dll";
wchar_t default_key[] = L"ABCDE";
wchar_t *key_str = default_key;
const size_t len = lstrlenW(key_str);
const size_t key_size = len * sizeof(key_str[0]);
const wchar_t *filename1 = (const wchar_t *)"enc_calc.enc";
const wchar_t *filename2 = (const wchar_t *)"calc.dll";
HANDLE hInpFile = CreateFileW(filename1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hInpFile == INVALID_HANDLE_VALUE) {
printf("Cannot open input file!\n");
system("pause");
return (-1);
}
HANDLE hOutFile = CreateFileW(filename2, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOutFile == INVALID_HANDLE_VALUE) {
printf("Cannot open output file!\n");
system("pause");
return (-1);
}
DWORD dwStatus = 0;
BOOL bResult = FALSE;
wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider";
HCRYPTPROV hProv;
if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
dwStatus = GetLastError();
printf("CryptAcquireContext failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
HCRYPTHASH hHash;
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
dwStatus = GetLastError();
printf("CryptCreateHash failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
if (!CryptHashData(hHash, (BYTE*)key_str, key_size, 0)) {
DWORD err = GetLastError();
printf("CryptHashData Failed : %#x\n", err);
system("pause");
return (-1);
}
printf("[+] CryptHashData Success\n");
HCRYPTKEY hKey;
if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0, &hKey)) {
dwStatus = GetLastError();
printf("CryptDeriveKey failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
printf("[+] CryptDeriveKey Success\n");
const size_t chunk_size = IN_CHUNK_SIZE;
BYTE *chunk = new BYTE[chunk_size];
DWORD out_len = 0;
BOOL isFinal = FALSE;
DWORD readTotalSize = 0;
DWORD inputSize = GetFileSize(hInpFile, NULL);
while (bResult = ReadFile(hInpFile, chunk, IN_CHUNK_SIZE, &out_len, NULL)) {
if (0 == out_len) {
break;
}
readTotalSize += out_len;
if (readTotalSize >= inputSize) {
isFinal = TRUE;
printf("Final chunk set, len: %d = %x\n", out_len, out_len);
}
if (!CryptDecrypt(hKey, NULL, isFinal, 0, chunk, &out_len)) {
printf("[-] CryptDecrypt failed: %x\n", GetLastError());
break;
}
DWORD written = 0;
if (!WriteFile(hOutFile, chunk, out_len, &written, NULL)) {
printf("writing failed!\n");
break;
}
memset(chunk, 0, chunk_size);
}
delete[]chunk; chunk = NULL;
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv, 0);
CloseHandle(hInpFile);
CloseHandle(hOutFile);
printf("Finished. Processed %#x bytes.\n", readTotalSize);
return 0;
}
The errors I'm getting are regarding the windows.h library, such as:
"ULONG does not name a type" and other types in windows. and at runtime: "Cannot Open input file", not sure why, even tho the file is downloaded in the current folder and I'm trying to open it as such in the code.

Problem with InternetOpenA (undefined reference to `___imp_InternetOpenA` [duplicate]

I want make C++ program where send .txt file with information to my PC. I surch so much in internet but cant find method that works.
When I uusing Dev C++ give me this errors:
...: undefined reference to __imp_InternetOpenA'
...: undefined reference to__imp_InternetConnectA'
...: undefined reference to __imp_FtpPutFileA'
...: undefined reference to__imp_HttpOpenRequestA'
Here are three examples where I find, but all return this error.
<pre>
#include <windows.h>
#include <wininet.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#pragma comment(lib,"wininet.lib")
#define ERROR_OPEN_FILE 10
#define ERROR_MEMORY 11
#define ERROR_SIZE 12
#define ERROR_INTERNET_OPEN 13
#define ERROR_INTERNET_CONN 14
#define ERROR_INTERNET_REQ 15
#define ERROR_INTERNET_SEND 16
using namespace std;
int main()
{
// Local variables
char filename[] = "file"; //Filename to be loaded
char filepath[] = "d:\\a.jpg"; //Filename to be loaded
char type[] = "image/jpeg";
char boundary[] = "--BOUNDARY---"; //Header boundary
char nameForm[] = "formname"; //Input form name
char iaddr[] = "localhost"; //IP address
char url[] = "/http/file.php"; //URL
char hdrs[512]={'-'}; //Headers
char * buffer; //Buffer containing file + headers
char * content; //Buffer containing file
FILE * pFile; //File pointer
long lSize; //File size
size_t result;
// Open file
pFile = fopen ( filepath , "rb" );
if (pFile==NULL)
{
printf("ERROR_OPEN_FILE");
getchar();
return ERROR_OPEN_FILE;
}
printf("OPEN_FILE\n");
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
content = (char*) malloc (sizeof(char)*lSize);
if (content == NULL)
{
printf("ERROR_MEMORY");
getchar();
return ERROR_OPEN_FILE;
}
printf("MEMORY_ALLOCATED\t \"%d\" \n",&lSize);
// copy the file into the buffer:
result = fread (content,1,lSize,pFile);
if (result != lSize)
{
printf("ERROR_SIZE");
getchar();
return ERROR_OPEN_FILE;
}
printf("SIZE_OK\n");
// terminate
fclose (pFile);
printf("FILE_CLOSE\n");
//allocate memory to contain the whole file + HEADER
buffer = (char*) malloc (sizeof(char)*lSize + 2048);
//print header
sprintf(hdrs,"Content-Type: multipart/form-data; boundary=%s",boundary);
sprintf(buffer,"%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%
----------
s\"\r\n",boundary,nameForm,filename);
sprintf(buffer,"%sContent-Type: %s\r\n",buffer,type);
sprintf(buffer,"%s%s",buffer,content);
sprintf(buffer,"%s--%s--\r\n",buffer,boundary);
//Open internet connection
HINTERNET hSession = InternetOpen("WINDOWS",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hSession==NULL)
{
printf("ERROR_INTERNET_OPEN");
getchar();
return ERROR_OPEN_FILE;
}
printf("INTERNET_OPENED\n");
HINTERNET hConnect = InternetConnect(hSession, iaddr,INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(hConnect==NULL)
{
printf("ERROR_INTERNET_CONN");
getchar();
return ERROR_INTERNET_CONN;
}
printf("INTERNET_CONNECTED\n");
HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",_T(url),NULL, NULL, NULL,INTERNET_FLAG_RELOAD, 1);
if(hRequest==NULL)
{
printf("ERROR_INTERNET_REQ");
getchar();
}
printf("INTERNET_REQ_OPEN\n");
BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, strlen(buffer));
if(!sent)
{
printf("ERROR_INTERNET_SEND");
getchar();
return ERROR_INTERNET_CONN;
}
printf("INTERNET_SEND_OK\n");
//close any valid internet-handles
InternetCloseHandle(hSession);
InternetCloseHandle(hConnect);
InternetCloseHandle(hRequest);
getchar();
return 0;
}
<pre>
#include <winsock2.h>
#include <wininet.h>
#include <tchar.h>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
//#pragma comment(lib,"wininet.lib")
using namespace std;
int main()
{
static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"C:\test.txt\"\nContent-Type: text/plain\n\nfile contents here\n-----------------------------7d82751e2bc0858--";
static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858";
HINTERNET hSession = InternetOpen("MyAgent",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hSession==NULL)
{
cout<<"Error: InternetOpen";
}
HINTERNET hConnect = InternetConnect(hSession, _T("localhost"),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(hConnect==NULL)
{
cout<<"Error: InternetConnect";
}
HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",_T("upload.php"), NULL, NULL, (const char**)"*/*\0", 0, 1);
if(hRequest==NULL)
{
cout<<"Error: HttpOpenRequest";
}
BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
if(!sent)
{
cout<<"Error: HttpSendRequest";
}
//close any valid internet-handles
InternetCloseHandle(hSession);
InternetCloseHandle(hConnect);
InternetCloseHandle(hRequest);
return 0;
}
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#include <iostream>
#define ERROR_OPEN_FILE 10
#define ERROR_MEMORY 11
#define ERROR_SIZE 12
#define ERROR_INTERNET_OPEN 13
#define ERROR_INTERNET_CONN 14
#define ERROR_INTERNET_REQ 15
#define ERROR_INTERNET_SEND 16
using namespace std;
int main()
{
// Local variables
static char filename[] = "test.txt"; //Filename to be loaded
static char type[] = "image/jpg";
static char boundary[] = "pippo"; //Header boundary
static char nameForm[] = "uploadedfile"; //Input form name
static char iaddr[] = "localhost"; //IP address
static char url[] = "test.php"; //URL
char hdrs[255]; //Headers
char * buffer; //Buffer containing file + headers
char * content; //Buffer containing file
FILE * pFile; //File pointer
long lSize; //File size
size_t result;
// Open file
pFile = fopen ( filename , "rb" );
if (pFile==NULL) return ERROR_OPEN_FILE;
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
content = (char*) malloc (sizeof(char)*lSize);
if (content == NULL) return ERROR_MEMORY;
// copy the file into the buffer:
result = fread (content,1,lSize,pFile);
if (result != lSize) return ERROR_SIZE;
// terminate
fclose (pFile);
//allocate memory to contain the whole file + HEADER
buffer = (char*) malloc (sizeof(char)*lSize + 2048);
//print header
sprintf(hdrs,"Content-Type: multipart/form-data; boundary=%s",boundary);
sprintf(buffer,"--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n",boundary,nameForm,filename);
sprintf(buffer,"%sContent-Type: %s\r\n\r\n",buffer,type);
sprintf(buffer,"%s%s\r\n",buffer,content);
sprintf(buffer,"%s--%s--\r\n",buffer,boundary);
//Open internet connection
HINTERNET hSession = InternetOpen("WinSock",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hSession==NULL) return ERROR_INTERNET_OPEN;
HINTERNET hConnect = InternetConnect(hSession, iaddr,INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(hConnect==NULL) return ERROR_INTERNET_CONN;
HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",url, NULL, NULL, (const char**)"*/*\0", 0, 1);
if(hRequest==NULL) return ERROR_INTERNET_REQ;
BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, strlen(buffer));
if(!sent) return ERROR_INTERNET_SEND;
//close any valid internet-handles
InternetCloseHandle(hSession);
InternetCloseHandle(hConnect);
InternetCloseHandle(hRequest);
return 0;
}
</pre>
I had many errors like this on my first C++ program. It is a problem with linking against the WinINet library. If you are using MinGW add "-lwininet" (without quotes) to the additional commandling arguments and it should be fixed. I don't know what to to do if you use VC++. Also, make sure the location of the WinINet library is in the linker's search paths.
With CMake you simply need
target_link_libraries( MY_TARGET
ws2_32)

Hwid to clipboard

So this is what i am trying todo i am trying to copy serial number to clipboard but it doesnt work is there anything i did wrong if yes then plz help me i would like to have this working becouse its something for a project of me that i am selling
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "windows.h"
namespace std {}
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformation(
_T("C:\\"),
volumeName,
ARRAYSIZE(volumeName),
& serialNumber,
& maxComponentLen,
& fileSystemFlags,
fileSystemName,
ARRAYSIZE(fileSystemName)))
{
_tprintf(_T("Serial Number: %lu\n"), serialNumber);
GlobalUnlock(GetVolumeInformation);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(1, GetVolumeInformation);
CloseClipboard();
MessageBoxA(NULL, "HWID COPYED.", "HWID", NULL);
std::cout << std::endl << "Press any key to continue...";
getchar();
}
}
You should avoid using the T macros (the macros starting with _T and _t). Microsoft still uses these macros in some of its documentations for historical reasons, but it's useless and confusing. I don't know if you are using ANSI or Unicode (Unicode is recommended).
If you only need the serial number from GetVolumeInformation then you can set the other variables to NULL, see documentation.
Once you get the serial number, convert it to text. Then copy the text to clipboard. Below is ANSI example:
void copy(const char* text)
{
int len = strlen(text) + 1;
HGLOBAL hmem = GlobalAlloc(GMEM_MOVEABLE, len);
char* buffer = (char*)GlobalLock(hmem);
strcpy_s(buffer, len, text);
GlobalUnlock(hmem);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, hmem);
CloseClipboard();
}
int _tmain()
{
DWORD serialNumber = 0;
if (GetVolumeInformation(
_T("C:\\"),
NULL,
0,
&serialNumber,
NULL,
0,
NULL,
0))
{
std::cout << serialNumber << std::endl;
char buf[100];
sprintf_s(buf, 100, "%d", serialNumber);
copy(buf);
MessageBoxA(NULL, buf, "HWID", NULL);
}
return 0;
}

C++ FTP writing to file is not working

I wrote this code that is SUPPOSED to write to a file on an ftp server, but it doesn't work. The file stays 0 bytes. There are also no errors. Here's my code:
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
int main()
{
int error=0;
char buffer[256];
char *text="Hello world.";
HINTERNET hOpen=InternetOpen("",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,INTERNET_FLAG_PASSIVE);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hOpen:%d:%s\n",error,buffer);
HINTERNET hConnect=InternetConnect(hOpen,"diabloip.host22.com",INTERNET_DEFAULT_FTP_PORT,"MY_USER_NAME","MY_PASSWORD",INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hConnect:%d:%s\n",error,buffer);
HINTERNET hFile=FtpOpenFile(hConnect,"diabloip.host22.com/public_html/log.txt",GENERIC_WRITE,FTP_TRANSFER_TYPE_ASCII,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hFile:%d:%s\n",error,buffer);
InternetWriteFile(hFile,text,strlen(text),NULL);
return 0;
}
The problem is passing NULL as the last parameter to InternetWriteFile. It is not an optional parameter and if you had error checking for that call as the rest you'd see GetLastError returns 87, or ERROR_INVALID_PARAMETER.
This works correctly and cleans up some of the other issues with incorrect parameters and the excessive casting that masks the issues.
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#pragma comment(lib, "wininet.lib")
void PrintStatus(const char* title)
{
DWORD error = 0;
DWORD sz = 256;
char buffer[256];
InternetGetLastResponseInfo(&error, buffer, &sz);
printf("%s:%u:%s\n", title, error, buffer);
}
int main()
{
const char *text = "Hello world.";
HINTERNET hOpen = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_PASSIVE);
PrintStatus("hOpen");
HINTERNET hConnect = InternetConnect(hOpen, "localhost", INTERNET_DEFAULT_FTP_PORT, "test", "test", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
PrintStatus("hConnect");
HINTERNET hFile = FtpOpenFile(hConnect, "log.txt", GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
PrintStatus("hFile");
DWORD wb = 0;
BOOL Success = InternetWriteFile(hFile, text, strlen(text), &wb);
if(!Success)
{
DWORD err = GetLastError();
printf("InternetWriteFile - Error = %u\n", err);
}
PrintStatus("InternetWriteFile");
InternetCloseHandle(hOpen);
return 0;
}

Why does my CryptDecrypt fail with error code 0x80090005 (NTE_BAD_DATA)?

I wrote this piece of code to decrypt a given cipher using a given key and iv. It works fine until CryptDecrypt which returns false and GetLastError() returns 0x80090005 (which should be NTE_BAD_DATA).
#include <Windows.h>
#include <wincrypt.h>
struct AesKey
{
BLOBHEADER Header;
DWORD dwKeyLength;
BYTE cbKey[16];
AesKey()
{
ZeroMemory(this, sizeof(*this));
Header.bType = PLAINTEXTKEYBLOB;
Header.bVersion = CUR_BLOB_VERSION;
Header.reserved = 0;
Header.aiKeyAlg = CALG_AES_128;
dwKeyLength = 16;
}
};
void AesDecrypt(unsigned char *output, unsigned char *input, int inLen, unsigned char *key, unsigned char *iv, int &plainSize)
{
HCRYPTPROV provider;
AesKey rawKey;
HCRYPTKEY cKey;
BOOL hr = CryptAcquireContext(&provider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0);
if (hr == FALSE)
throw "Unable to acquire AES Context";
for (int i = 0; i < 16; i++)
rawKey.cbKey[i] = key[i];
hr = CryptImportKey(provider, (BYTE *) &rawKey, sizeof(AesKey), NULL, 0, &cKey);
if (hr == FALSE)
throw "Unable to import given key";
hr = CryptSetKeyParam(cKey, KP_IV, (BYTE *) iv, 0);
if (hr == FALSE)
throw "Unable to set IV";
DWORD dwMode = CRYPT_MODE_CBC;
hr = CryptSetKeyParam(cKey, KP_MODE, (BYTE*) &dwMode, 0);
if (hr == FALSE)
throw "Unable to set mode";
memcpy(output, input, inLen);
DWORD d = (DWORD) inLen;
hr = CryptDecrypt(cKey, NULL, TRUE, 0, output, &d);
if (hr == FALSE)
{
int err = GetLastError();
throw "Error during Decryption";
}
plainSize = d;
}
If you have any idea, please share :)
Thanks in advance...