📄 encryptor.cpp
字号:
//--------------------------------------------------------------------
// End the do loop when the last block of the source file has been
// read, encrypted, and written to the destination file.
printf("DONE!\r\n");
}
catch(const char* msg)
{
printf("FAILED!\r\n");
if(hSource)
fclose(hSource);
if(hDestination)
fclose(hDestination);
hSource = NULL;
hDestination = NULL;
if(GetFileAttributes(bakFile) != INVALID_FILE_ATTRIBUTES)
MoveFileEx(bakFile,file,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH);
HandleError(msg);
}
//--------------------------------------------------------------------
// Close files.
if(hSource)
fclose(hSource);
if(hDestination)
{
handle = (HANDLE)_get_osfhandle(_fileno(hDestination));
SetFileTime(handle,&createTime,&accessTime,&modifyTime);
fclose(hDestination);
}
//--------------------------------------------------------------------
// Free memory.
if(pbBuffer)
free(pbBuffer);
//--------------------------------------------------------------------
// Destroy session key.
if(hKey)
CryptDestroyKey(hKey);
//--------------------------------------------------------------------
// Destroy hash object.
if(hHash)
CryptDestroyHash(hHash);
//--------------------------------------------------------------------
// Release provider handle.
if(hCryptProv)
CryptReleaseContext(hCryptProv, 0);
DeleteFile(bakFile);
return(TRUE);
} // End of Encryptfile
//--------------------------------------------------------------------
// Define the function Decryptfile.
static BOOL decryptFile(
const CString file,
const char* szPassword)
{
//--------------------------------------------------------------------
// Declare and initialize local variables.
int hSource;
int hDestination;
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
PBYTE pbKeyBlob = NULL;
PBYTE pbBuffer=NULL;
DWORD dwBlockLen;
DWORD dwBufferLen;
DWORD dwCount;
BOOL status = FALSE;
CString bakFile = file+".temp";
HANDLE handle = INVALID_HANDLE_VALUE;
FILETIME createTime,lastAccessTime,lastWriteTime;
try
{
MoveFile(file,bakFile);
printf("decrypting %s ... ", file);
hSource = _open( bakFile, _O_RDONLY|_O_BINARY );
if(hSource == -1)
{
throw("Error opening source cipher file!");
}
handle = (HANDLE)_get_osfhandle(hSource);
GetFileTime(handle,&createTime,&lastAccessTime,&lastWriteTime);
//--------------------------------------------------------------------
// Open destination file.
hDestination = _open(file,_O_CREAT|_O_BINARY|_O_WRONLY,_S_IREAD | _S_IWRITE );
if(hDestination == -1)
{
throw("Error opening destination plaintext file!");
}
//--------------------------------------------------------------------
// Get a handle to the default provider.
if(!CryptAcquireContext(
&hCryptProv,
NULL,
NULL,
PROV_DH_SCHANNEL,
CRYPT_VERIFYCONTEXT ))
{
throw("Error during CryptAcquireContext!");
}
//--------------------------------------------------------------------
// Check for existence of a password.
//--------------------------------------------------------------------
// Decrypt the file with a session key derived from a password.
//--------------------------------------------------------------------
// Create a hash object.
if(!CryptCreateHash(
hCryptProv,
CALG_MD5,
0,
0,
&hHash))
{
throw("Error during CryptCreateHash!");
}
//--------------------------------------------------------------------
// Hash in the password data.
if(!CryptHashData(
hHash,
(BYTE *)szPassword,
(DWORD)strlen(szPassword),
0))
{
throw("Error during CryptHashData!");
}
//--------------------------------------------------------------------
// Derive a session key from the hash object.
if(!CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey))
{
throw("Error during CryptDeriveKey!");
}
//--------------------------------------------------------------------
// Destroy the hash object.
CryptDestroyHash(hHash);
hHash = 0;
//--------------------------------------------------------------------
// The decryption key is now available, either having been imported
// from a BLOB read in from the source file or having been created
// using the password. This point in the program is not reached if
// the decryption key is not available.
//--------------------------------------------------------------------
// Determine the number of bytes to decrypt at a time.
// This must be a multiple of ENCRYPT_BLOCK_SIZE.
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
dwBufferLen = dwBlockLen;
//--------------------------------------------------------------------
// Allocate memory.
if(!(pbBuffer = (BYTE *)malloc(dwBufferLen)))
{
throw("Out of memory!\n");
}
//--------------------------------------------------------------------
// Decrypt source file, and write to destination file.
dwCount = _read(
hSource,
pbBuffer,
MAX_PASS_BUF
);
CryptDecrypt(
hKey,
0,
TRUE,
0,
pbBuffer,
&dwCount);
if(dwCount != MAX_PASS_LEN || strcmp(szPassword,(const char*)pbBuffer))
{
printf ("password is incorrect!\r\nany key stop");
if(hSource!=-1)
_close(hSource);
if(hDestination!=-1)
_close(hDestination);
hSource = -1;
hDestination = -1;
if(GetFileAttributes(bakFile) != INVALID_FILE_ATTRIBUTES)
MoveFileEx(bakFile,file,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH);
getch();
return FALSE;
}
do {
//--------------------------------------------------------------------
// Read up to dwBlockLen bytes from source file.
dwCount = _read(
hSource,
pbBuffer,
dwBlockLen);
if(dwCount == -1)
{
throw("Error reading ciphertext!");
}
//--------------------------------------------------------------------
// Decrypt data.
int ef = _eof(hSource);
if(!CryptDecrypt(
hKey,
0,
ef,
0,
pbBuffer,
&dwCount))
{
throw("Error during CryptDecrypt!");
}
//--------------------------------------------------------------------
// Write data to destination file.
dwCount = _write(
hDestination,
pbBuffer,
dwCount);
if(dwCount == -1)
{
throw("Error writing plaintext!");
}
}
while(!_eof(hSource));
status = TRUE;
printf("DONE!\r\n");
}
catch(const char * msg)
{
printf("FAILED!\r\n");
if(hSource)
_close(hSource);
if(hDestination)
_close(hDestination);
hSource = NULL;
hDestination = NULL;
if(GetFileAttributes(bakFile) != INVALID_FILE_ATTRIBUTES)
MoveFileEx(bakFile,file,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH);
HandleError(msg);
}
//--------------------------------------------------------------------
// Close files.
if(hSource!=-1)
_close(hSource);
if(hDestination!=-1)
{
handle = (HANDLE)_get_osfhandle(hDestination);
SetFileTime(handle,&createTime,&lastAccessTime,&lastWriteTime);
_close(hDestination);
}
//--------------------------------------------------------------------
// Free memory.
if(pbKeyBlob)
free(pbKeyBlob);
if(pbBuffer)
free(pbBuffer);
//--------------------------------------------------------------------
// Destroy session key.
if(hKey)
CryptDestroyKey(hKey);
//--------------------------------------------------------------------
// Destroy hash object.
if(hHash)
CryptDestroyHash(hHash);
//--------------------------------------------------------------------
// Release provider handle.
if(hCryptProv)
CryptReleaseContext(hCryptProv, 0);
DeleteFile(bakFile);
return status;
} // End of Decryptfile
//find is a string str end with end
BOOL stringEndWith(CString str,CString end)
{
if(str.GetLength() < end.GetLength())
return FALSE;
const char* pszStr = str;
const char* pszEnd = end;
return !strcmp(pszStr+str.GetLength()-end.GetLength(),pszEnd);
}
void formatError(int code)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
printf((LPCTSTR)lpMsgBuf);
LocalFree( lpMsgBuf );
}
//--------------------------------------------------------------------
// This example uses the function HandleError, a simple error
// handling function, to print an error message to the standard error
// (stderr) file and exit the program.
// For most applications, replace this function with one
// that does more extensive error reporting.
void HandleError(const char *s)
{
fprintf(stderr,"An error occurred in running the program. \n");
fprintf(stderr,"%s\n",s);
fprintf(stderr, "Error number %x.\n", GetLastError());
fprintf(stderr, "Program terminating. \n");
formatError(GetLastError());
printf("any key to exit");
getch();
//exit(1);
} // End of HandleError
void addRegister()
{
HKEY resultKey;
HKEY subkey;
DWORD disp;
long res = RegCreateKeyEx(HKEY_CLASSES_ROOT,
"*\\shell\\encrypt",0,NULL,0,KEY_ALL_ACCESS,NULL,&resultKey,&disp);
// formatError(res);
res = RegSetValueEx(resultKey,NULL,0,REG_SZ,(const BYTE*)"加密(&F)",8);
// formatError(res);
res = RegCreateKeyEx(resultKey,"command",0,NULL,0,KEY_ALL_ACCESS,NULL,&subkey,&disp);
// formatError(res);
char sz[MAX_PATH+50];
ZeroMemory(sz,MAX_PATH+50);
int len = GetModuleFileName(NULL,sz,MAX_PATH);
if(len==0)
return;
sz[len] = 0;
strcat(sz," /e \"%1\"");
res = RegSetValueEx(subkey,NULL,0,REG_SZ,(const BYTE*)sz,(DWORD)strlen(sz));
// formatError(res);
RegCloseKey(resultKey);
RegCloseKey(subkey);
res = RegCreateKeyEx(HKEY_CLASSES_ROOT,
"Directory\\shell\\encrypt",0,NULL,0,KEY_ALL_ACCESS,NULL,&resultKey,&disp);
res = RegSetValueEx(resultKey,NULL,0,REG_SZ,(const BYTE*)"加密(&F)",8);
res = RegCreateKeyEx(resultKey,"command",0,NULL,0,KEY_ALL_ACCESS,NULL,&subkey,&disp);
res = RegSetValueEx(subkey,NULL,0,REG_SZ,(const BYTE*)sz,(DWORD)strlen(sz));
RegCloseKey(resultKey);
RegCloseKey(subkey);
res = RegCreateKeyEx(HKEY_CLASSES_ROOT,
"*\\shell\\decrypt",0,NULL,0,KEY_ALL_ACCESS,NULL,&resultKey,&disp);
res = RegSetValueEx(resultKey,NULL,0,REG_SZ,(const BYTE*)"解密(&D)",8);
res = RegCreateKeyEx(resultKey,"command",0,NULL,0,KEY_ALL_ACCESS,NULL,&subkey,&disp);
sz[len] = 0;
strcat(sz," /d \"%1\"");
res = RegSetValueEx(subkey,NULL,0,REG_SZ,(const BYTE*)sz,(DWORD)strlen(sz));
RegCloseKey(resultKey);
RegCloseKey(subkey);
res = RegCreateKeyEx(HKEY_CLASSES_ROOT,
"Directory\\shell\\decrypt",0,NULL,0,KEY_ALL_ACCESS,NULL,&resultKey,&disp);
res = RegSetValueEx(resultKey,NULL,0,REG_SZ,(const BYTE*)"解密(&D)",8);
res = RegCreateKeyEx(resultKey,"command",0,NULL,0,KEY_ALL_ACCESS,NULL,&subkey,&disp);
res = RegSetValueEx(subkey,NULL,0,REG_SZ,(const BYTE*)sz,(DWORD)strlen(sz));
RegCloseKey(resultKey);
RegCloseKey(subkey);
try{
HCRYPTPROV hCryptProv;
if(CryptAcquireContext(
&hCryptProv,
NULL,
NULL,
PROV_DH_SCHANNEL,
CRYPT_NEWKEYSET))
CryptReleaseContext(hCryptProv, 0);
}
catch(...)
{
formatError(GetLastError());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -