|
Have a look at the SetWindowsHookEx() function.
Nobody can give you wiser advice than yourself. - Cicero
ப்ரம்மா
|
|
|
|
|
I am trying to build a cryptography program using HMACSHA256 as the verification technique. I came across this article by Nathan Blomquist and here's the link:
File Encryption/Decryption with Hash Verification in C#
http://www.codeproject.com/csharp/fileencryptdecrypt.asp
I edited the code to use HMACSHA256 instead as well as C++. Upon decryption using the incorrect password, I will encounter this error.
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Padding is invalid and cannot be removed.
Below is my code and the error occurs at this line
while ( (bytesInCurrentBlock = cin->Read(buffer, 0, buffer->Length)) != 0 )
in the DecryptFile function. I would be grateful if someone could point out my mistake here.
PS: I am suppose to be expecting the hmacsha256 mismatch error to throw instead
<code>void CryptoData::EncryptFile(String^ inFile, String^ outFile, String^ password, int keySize,
CryptoProgressCallBack^ callback)
{
FileStream^ fin = gcnew FileStream(inFile, FileMode::Open, FileAccess::Read);
FileStream^ fout = gcnew FileStream(outFile, FileMode::OpenOrCreate, FileAccess::Write);
fout->SetLength(0);
array<Byte>^ buffer = gcnew array<Byte>(BUFFER_SIZE);
int bytesInCurrentBlock;
long long bytesProcessed = 0;
long long fileLength = fin->Length;
long progress;
// generate IV and Salt
array<Byte>^ IV = GenerateRandomBytes(16);
array<Byte>^ salt = GenerateRandomBytes(16);
// create the crypting object
SymmetricAlgorithm^ sma = CreateRijndaelManaged(password, keySize, IV, salt);
// write the IV and salt to the beginning of the file
fout->Write(IV, 0, IV->Length);
fout->Write(salt, 0, salt->Length);
// Initialize the keyed hash object.
HashAlgorithm^ hmacsha256 = gcnew HMACSHA256(sma->Key);
// Compute the hash of the input file.
array<Byte>^ hashValue = hmacsha256->ComputeHash(fin);
// Reset fin to the beginning of the file.
fin->Position = 0;
// Write the computed hash value to the output file.
fout->Write(hashValue, 0, hashValue->Length);
// create the cryptostream
CryptoStream^ cout = gcnew CryptoStream(fout, sma->CreateEncryptor(), CryptoStreamMode::Write);
// read and write the bytes to the crypto stream in BUFFER_SIZE chunks
while ( (bytesInCurrentBlock = fin->Read(buffer, 0, buffer->Length)) != 0 )
{
cout->Write(buffer, 0, bytesInCurrentBlock);
bytesProcessed += bytesInCurrentBlock;
progress = (int)((bytesProcessed / fileLength) * 100);
callback(0, 100, progress);
}
// clear the hashing object
hmacsha256->Clear();
// flush and close the cryptostream
cout->Flush();
cout->Close();
// close the input file
fin->Close();
}
void CryptoData::DecryptFile(String^ inFile, String^ outFile, String^ password, int keySize,
CryptoProgressCallBack^ callback)
{
FileStream^ fin = gcnew FileStream(inFile, FileMode::Open, FileAccess::Read);
FileStream^ fout = gcnew FileStream(outFile, FileMode::OpenOrCreate, FileAccess::Write);
fout->SetLength(0);
array<Byte>^ buffer = gcnew array<Byte>(BUFFER_SIZE);
int bytesInCurrentBlock;
long long bytesProcessed = 0;
long long fileLength = fin->Length;
int progress;
// read the IV and Salt
array<Byte>^ IV = gcnew array<Byte>(16);
fin->Read(IV, 0, 16);
array<Byte>^ salt = gcnew array<Byte>(16);
fin->Read(salt, 0, 16);
// create the crypting object
SymmetricAlgorithm^ sma = CreateRijndaelManaged(password, keySize, IV, salt);
// Initialize the keyed hash object.
HashAlgorithm^ hmacsha256 = gcnew HMACSHA256(sma->Key);
// Create an array to hold the keyed hash value read from the file.
array<Byte>^ storedHash = gcnew array<Byte>(hmacsha256->HashSize / 8);
// Read in the storedHash.
fin->Read(storedHash, 0, storedHash->Length);
bytesProcessed = 64;
// create the cryptostream that will process the file
CryptoStream^ cin = gcnew CryptoStream(fin, sma->CreateDecryptor(), CryptoStreamMode::Read);
// read the BUFFER_SIZE chunks
while ( (bytesInCurrentBlock = cin->Read(buffer, 0, buffer->Length)) != 0 )
{
fout->Write(buffer, 0, bytesInCurrentBlock);
bytesProcessed += bytesInCurrentBlock;
progress = (int)((bytesProcessed / fileLength) * 100);
callback(0, 100, progress);
}
// Reposition the file to compute the hash of the output file.
fout->Position = 0;
array<Byte>^ computedHash = hmacsha256->ComputeHash(fout);
if (!ByteArrayEqual(computedHash, storedHash)) {
throw gcnew CryptoDataException("hmacsha256 mismatch");
}
// flush and close the cryptostream
cin->Flush();
cin->Close();
// close the output file
fout->Close();
}
</code>
-- modified at 5:09 Wednesday 20th December, 2006
|
|
|
|
|
Hi all,
can ne one tell me how to create a 2-dimensional array of strings
thnx
|
|
|
|
|
char x[][10]={"fsfhg",
"abc"
};
never say die
|
|
|
|
|
std::vector<std::vector<std::string> > vec2D;
|
|
|
|
|
or u can go for char(*p)[20]
never say die
|
|
|
|
|
In addition to what toxcct said, you can create a class to help with the details of your specific requirements; see vector of vectors for rows and fields[^] for a beginning of what can be done.
|
|
|
|
|
i m making a sdi application in that application there are splitter windows .
In one of the splitter window there is a list ctrl.That list ctrl is made by making a object of a class which is in turn derived frm CListCtrl class and then calling Create function...
/*******************/
CColoredListCtrl List_Object_Ctrl;
List_Object_Ctrl.Create(LVS_REPORT | LVS_SHOWSELALWAYS | LBS_NOTIFY ,
CRect(300,300,800,600), this, 1);
List_Object_Ctrl.InsertColumn(0,"Name",150,150);
/**************************************/
Now what i m trying to do is i am opening a dialog box using my toolbar ......
void CSplitterWndTestApp::OnNewTask()
{
CNewTaskDialog obj_NewTask;
if(obj_NewTask.DoModal() == IDOK)
{
ptr->addin();
}
}
when onok is clicked i want that some items s'ld go and add up in list ctrl
for which i m calling a function addin which is made in the class derived from list ctrl....(CColoredListCtrl )
In addin function these two lines are written
void CColoredListCtrl::addin()
{
InsertItem(0,"test",NULL);
SetItemText(0,1,"str");
}
Now my problem is when the pointer passes its ctrl in that function.
and when insert item is called it gives an error of access violation .....
i have made object ptr extern
n allocated it memory in its own class CColouredListCtrl like this
int CColoredListCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CListCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
ptr=this;
return 0;
}
can anybody help me with this......
|
|
|
|
|
neha.agarwal27 wrote: ptr->addin();
did u check the value of ptr at the above statement through debugging?
nave
|
|
|
|
|
hi
This is Apoorva raje.I am facing a problem with SqlExecuteDirect() function, my piece of code is doing deleting all the recods from 12 different table and then insert new records in those tables. each table will have approximate 100 to 1,00,000 records .For deletion i copy the query into a char array and then first allocate a statement handle execute it by SqlExecuteDirect()function and then free the statement handle but even we are freeing the statement handle the memory is not freed and its accumulating around 12mb. the code is given below:
//delete ARCDataSet //Same code for deleting data for 12 other tables
rc = SQLAllocHandle(SQL_HANDLE_STMT,ConHandle,&StmtHandle);
memset(szSQL,0,1024);
sprintf(szSQL,"delete from ARCDataSet");
rc = SQLExecDirect(StmtHandle,(SQLCHAR*)szSQL,strlen(szSQL));
rc = SQLFreeHandle(SQL_HANDLE_STMT,StmtHandle);
//
rc = SQLAllocHandle(SQL_HANDLE_STMT,ConHandle,&StmtHandle);
memset(szSQL,0,1024);
int m_Dsq =0;
m_Dsq = atoi(((ARCAdminDlg*)(AfxGetMainWnd()))->mp_ARCSecDb->m_chDSQ );
sprintf(szSQL,"INSERT INTO ARCDS (ARCDSQ,DBServer,DBSuperUser,DBSuPwd,DBSignature,DBComments,nDsq,noCats,noTabs,noCols,noSTC,noScopes,noDataSets,noEntrances,noEntSets,noPermits) values (\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',%d ,%d , %d, %d,%d ,%d , %d,%d ,%d, %d );"
rc = SQLExecDirect(StmtHandle,(SQLCHAR*)szSQL,strlen(szSQL));
rc = SQLFreeHandle(SQL_HANDLE_STMT,StmtHandle);
// 3.1 end parameters writing into ARCDS
------------------ user details start ------------------------------------*/
// 3.2 begin Isert into Security db , user details
rc = SQLAllocHandle(SQL_HANDLE_STMT,ConHandle,&StmtHandle);
unsigned int nUsq = ((ARCAdminDlg*)(AfxGetMainWnd()))->mp_ARCSecDb->m_noUsers;
int iVal=0;
for ( int nIdx = 0; nIdx < 35000 ; nIdx++)
{
iVal=0;
memset(szSQL,0,1024);
sprintf(szSQL,"insert into ARCdstc (type,dstcSeq,ARCdstcName) values (\'%s\',%d,\'%s\')", chType, ((ARCAdminDlg*)(AfxGetMainWnd()))->mp_ARCSecDb-mp_arcTables[nIdx]->tsq , ((ARCAdminDlg*)(AfxGetMainWnd()))->mp_ARCSecDb->mp_arcTables[nIdx]->tableName
);
rc = SQLExecDirect(StmtHandle,(SQLCHAR*)szSQL,strlen(szSQL));
}
rc = SQLFreeHandle(SQL_HANDLE_STMT,StmtHandle);
// 3.2 end Isert into Security db , user details
//Same code to insert data into 10 other different tables.
Thanks in advance , i will be thankfull to all.
|
|
|
|
|
How is the memory for szSQL managed? I cannot see where it is allocated and freed.
Some optimization points, take them or leave them (ignoring buffer overrun protection that should be added):
1: You do not need to memset(...) the string buffer before you use it - sprintf(...) will NUL -terminiate it for you
2: Do not use sprintf(...) as a replacement for strcpy(...) (in fact, that static string does not really need to be copied to a buffer to be executed)
3: sprintf(...) returns the number of characters it put into the buffer, excluding the terminating NUL so you can use that value to eliminate the calls to strlen(...)
4: I would cache the result of ((ARCAdminDlg*)(AfxGetMainWnd()))->mp_ARCSecDb->mp_arcTables[nIdx] within the loop and not evaluate it multiple times.
In your loop body, implementing the tips in #1 and #3 will eliminate 70000 operations from your loop.
Peace!
-=- James If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong! Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road! DeleteFXPFiles & CheckFavorites (Please rate this post!)
|
|
|
|
|
Thanks a lot for ur reply szSQL is a character array declared as
char szSQL[1024]={0};
i have tried both the option but not much improvement in the memory accumulation. i suppose the problem is with
SQLFreeHandle(SQL_HANDLE_STMT,StmtHandle),it does not free the full memory which is been allcated by
rc = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&EnvHandle).
|
|
|
|
|
I would like to know if some one has goe got a clue to how to do Image segmentation.
Rishikant
|
|
|
|
|
|
Hi all,
When I run my application, I receive the following error:
The application failed to initialize properly (0xc0150002). Click OK to terminate the apllication.
What can i do to make this work??
Many thanx
The only programmers that are better than C programmers are those who code in 1's and 0's.....
Programm3r
|
|
|
|
|
|
|
Hi,
Did you check it in second folder ? VS2005 has different folder structure - one Debug/Release foder is in solution folder and the second in project.
And the thread which you reffered ... you wrote that you solved the problem.
You wrote that problem occurs sometimes - perhaps some pointers are not valid or incorect initialized - try to detect which function or which line causes crashes (you can e.g. create an log file)
-----------
Mila
|
|
|
|
|
Thanks for the response Mila,
Maybe I didn't expressed myself correctly. The only thing I want to know is, the principle behind the compiling of a project when using VS2005, in the sense that the CRT dll's cause problems when transfering an exe to another computer. How to prevent it ... I have read articles about that, but those articles did not answer my question. And what steps I can follow to prevent such an occurance.
The previous thread was just for background information, Yes I said that I solved it, but that was till I wrote the next application, and it happened again.
Many thanx
Regards
-- modified at 0:21 Thursday 21st December, 2006
The only programmers that are better than C programmers are those who code in 1's and 0's.....
Programm3r
|
|
|
|
|
hi
I have ATL ActiveX Control.I have placed Dialog box in that.I want to Display an ActiveX Control on that dialog.The ActiveX Control is not visible in Shared but it is visible in static Linking.
I have placed AfxEnableControlContainer but even then there seems to be problem with shared.is there any equivalent for AfxEnableControlContainer in Shared Dll?
how to display ActiveX on another ActiveX in shared mode?
Any links wud do fine...
Thanx in advance
"Every morning I go through Forbes list of 40 richest people in the world. If my name is not in there, I go to work..!!!"
|
|
|
|
|
Hi Guys,
Can anyone tell my how can i create a Global Desktop that can be used by all the users of a system.
I wanna do it programmatically using VC++....
Thanks
~ Selva
|
|
|
|
|
Hello,
i have an litle CListBox control on my dialog, and i like to show items with the gridlines,
ist that posible,i can't find any params to set and show this style?
Any one have some sugestions for me?
regards
break;
|
|
|
|
|
m_ListCtrl.SetExtendedStyle(LVS_EX_GRIDLINES);
mind you sometimes it doesn't work well in XP with theme enabled.
Used on me in a bar: Have you considered suing your brains for non-support?
|
|
|
|
|
Hello,
thanks for answer, but i dont mean the CListCtrl, i mean CListBox, and she dont have function like
SetExtendedStyle(...);
any other way or i dont understand what you mean?
regards
break;
|
|
|
|
|
AFAIK CListBox has not gridlines.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
|
|
|
|
|