Excerpt |
---|
Adding a secret key in a program file dynamically, it should not make any side effects on the program - the I had some projects needs to put its own secret key when they needed, and the secret key should not be exist as an alternative file or stored in any secret place in order to have mobility - meaning that application having a secret key should be able to use in any PC/Laptop. The easiest approach can do that is adding an additional information at the end of the binary file, below . |
Below code shows the way to save the necessary secret information in Delphi.
...
Following code enables you to hide secret key in a program fileFor your information, if you want to increase the size of the message, you should increase CK_MAX_MSG_LEN below.
Code Block | ||
---|---|---|
| ||
const CK_SINGATURE = '!CK!'; const CK_MAX_MSG_LEN = 1024; function CKReadPassword(sFileName:string):string; var sFile: TFileStream; lenPWD, lenPWD_old: WORD; sEncryptedPWD: AnsiString; buff: PAnsiChar; begin GetMem( buff, CK_MAX_MSG_LEN); ZeroMemory( buff, CK_MAX_MSG_LEN); if FileExists(sFileName) then begin lenPWD_old := 0; sFile := TFileStream.Create( sFileName, fmOpenRead); if sFile.Handle<>THandle(nil) then begin sFile.Seek( -4, soFromEnd); sFile.Read( PAnsiChar(buff)^, 4); if buff=CK_SINGATURE then begin // has master key, so need to erase it sFile.Seek( -6, soFromEnd); sFile.Read( lenPwd, 2); sFile.Seek( -(lenPWD + 6), soFromEnd); sFile.Read( PAnsIChar(buff)^, lenPWD); Result := trim(string(buff)); end; sFile.Destroy; end; end; FreeMem(buff); end; function CKUpdatePassword(sFileName, sPWD:String):Boolean; var sFile: TFileStream; lenPWD, lenPWD_old: WORD; sEncryptedPWD: AnsiString; buff: PAnsiChar; begin GetMem( buff, CK_MAX_MSG_LEN); ZeroMemory( buff, CK_MAX_MSG_LEN); if not FileExists(sFileName) then begin Result := False; end else begin lenPWD_old := 0; sFile := TFileStream.Create( sFileName, fmOpenReadWrite); if sFile.Handle<>THandle(nil) then begin sFile.Seek( -4, soFromEnd); sFile.Read( PAnsiChar(buff)^, 4); if buff=CK_SINGATURE then begin // has master key, so need to erase it sFile.Seek( -6, soFromEnd); sFile.Read( lenPwd, 2); sFile.Seek( -(lenPWD + 6), soFromEnd); lenPWD_old := lenPWD; end else sFile.Seek( 0, soFromEnd); while Length(sPWD)<lenPWD_old do sPWD := sPWD + ' '; sEncryptedPWD := AnsiString(sPWD); lenPWD := Length(sEncryptedPWD); sFile.Write( PAnsiChar(sEncryptedPWD)^, lenPWD); sFile.Write( lenPWD, 2); sFile.Write( PAnsiChar(CK_SINGATURE)^, 4); sFile.Destroy; Result := True; end else Result := False; end; FreeMem(buff); end; procedure TForm1.Button2Click(Sender: TObject); begin if not FileExists(eMasterFile.Text) then begin ShowMessage( 'Please select program file you want'); end else begin if (CKUpdatePassword( eMasterFile.Text, ePWD.Text)=True) then begin ShowMessage('Successfully Changed !!'); Close; end; end; end; |
...