📄 encryptor.cpp
字号:
// Encryptor.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <wincrypt.h>
#include <conio.h>
#include "afxwin.h"
#include "afxtempl.h"
#include "io.h"
#include "fcntl.h"
#include "sys/stat.h"
#define MAX_PASS_BUF 64
#define MAX_PASS_LEN (MAX_PASS_BUF-8)
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#define KEYLENGTH 0x00400000 //means 64bits
void HandleError(const char *s);
//--------------------------------------------------------------------
// These additional #define statements are required.
#define ENCRYPT_ALGORITHM CALG_DES
#define ENCRYPT_BLOCK_SIZE 8
BOOL stringEndWith(CString str,CString end);
void decryptDir( CString dir,const char* szPassword);
static BOOL decryptFile(
const CString file,
const char* szPassword);
void encryptDir( CString dir,const char* szPassword);
static BOOL encryptFile(
const CString file,
const char* szPassword);
void printUsage();
void addRegister();
int inputPassword(char* szPass/*suppse szPass is MAX_PASS_BUF length*/)
{
int count;
BOOL bReinput = FALSE;
do{
count = 0;
ZeroMemory(szPass,MAX_PASS_BUF);
char ch;
do{
ch = getch();
szPass[count] = ch;
}while(ch != 13 && (++count)<=MAX_PASS_LEN);
if(count>MAX_PASS_LEN)
{
printf("password too long,please input again:");
bReinput = TRUE;
}
}while(bReinput);
szPass[count] = 0;//char CR is not included in password
return count;
}
int main(int argc, _TCHAR* argv[])
{
addRegister();
if(argc < 2)
{
printUsage();
return 0;
}
int fileAttr = GetFileAttributes(argv[2]);
if(fileAttr == INVALID_FILE_ATTRIBUTES)
{
printf("%s is not a valid file or directory\r\n",argv[2]);
printUsage();
return 1;
}
BOOL bDir = FALSE;
if(fileAttr & FILE_ATTRIBUTE_DIRECTORY)
{
bDir = TRUE;
}
char szPass[MAX_PASS_BUF];
if(!strcmp(argv[1],"/d"))
{
printf("Input password(maximum 56 char):\r\n");
int count = inputPassword(szPass);
if(count == 0)
return 0;//no password is inputed,only return is entered
if(bDir)
decryptDir(argv[2],szPass);
else
decryptFile(argv[2],szPass);
}
else if(!strcmp(argv[1],"/e"))
{
char szPass2[MAX_PASS_BUF];
do
{
printf("Input password(maximum 56 char):\r\n");
int count = inputPassword(szPass);
if(count == 0)
return 0;
printf("Input again:\r\n");
inputPassword(szPass2);
}while(strcmp(szPass,szPass2) && puts("two password is not consistent!\r\n")>=0);
if(bDir)
encryptDir(argv[2],szPass);
else
encryptFile(argv[2],szPass);
}
else
printUsage();
return 0;
}
void printUsage()
{
printf("use:\r\nencrypt option dest\r\n");
printf(" option: /e to encrypt\r\n");
printf(" /d to decrypt\r\n");
printf(" dest is a file name or a directory path\r\n");
}
void decryptDir( CString dir,const char* szPassword)
{
if(stringEndWith(dir,"\\."))
return;
if(stringEndWith(dir,"\\.."))
return;
CFileFind finder;
BOOL bWorking = finder.FindFile(dir+"\\*.*");
if(!bWorking)
return;
CStringArray fileList;
fileList.SetSize(0,10);
while(bWorking)
{
bWorking = finder.FindNextFile();
if(finder.IsDirectory() )
{
if(dir!=finder.GetFilePath())
decryptDir(finder.GetFilePath(),szPassword);
continue;
}
//CString file = ;
fileList.Add(finder.GetFilePath());
}
for(int i=0;i<fileList.GetCount();i++)
{
decryptFile(fileList[i],szPassword);
}
}
void encryptDir( CString dir,const char* szPassword)
{
if(stringEndWith(dir,"\\."))
return;
if(stringEndWith(dir,"\\.."))
return;
CFileFind finder;
BOOL bWorking = finder.FindFile(dir+"\\*.*");
if(!bWorking)
return;
CStringArray fileList;
fileList.SetSize(0,10);
while(bWorking)
{
bWorking = finder.FindNextFile();
if(finder.IsDirectory() )
{
if(dir!=finder.GetFilePath())
encryptDir(finder.GetFilePath(),szPassword);
continue;
}
//CString file = ;
fileList.Add(finder.GetFilePath());
}
for(int i=0;i<fileList.GetCount();i++)
{
encryptFile(fileList[i],szPassword);
}
}
//--------------------------------------------------------------------
// Code for the function EncryptFile called by main.
static BOOL encryptFile(
const CString file,
const char* szPassword)
//--------------------------------------------------------------------
// Parameters passed are:
// szSource, the name of the input, a plaintext file.
// szDestination, the name of the output, an encrypted file to be
// created.
// szPassword, either NULL if a password is not to be used or the
// string that is the password.
{
//--------------------------------------------------------------------
// Declare and initialize local variables.
FILE *hSource;
FILE *hDestination;
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
PBYTE pbBuffer;
DWORD dwBlockLen;
DWORD dwBufferLen;
DWORD dwCount;
//--------------------------------------------------------------------
// Open source file.
HANDLE handle;
FILETIME createTime,modifyTime,accessTime;
CString bakFile = file+".temp";
MoveFile(file,bakFile);
try
{
if(hSource = fopen(bakFile,"rb"))
{
printf("Encrypting file %s ... ", file);
handle = (HANDLE)_get_osfhandle(_fileno(hSource));
BOOL b = GetFileTime(handle,&createTime,&accessTime,&modifyTime);
}
else
{
throw("Error opening source plaintext file!");
}
//--------------------------------------------------------------------
// Open destination file.
if(hDestination = fopen(file,"wb"))
{
//printf("Destination file %s is open. \n", file);
}
else
{
throw("Error opening destination ciphertext file!");
}
// Get handle to the default provider.
if(CryptAcquireContext(
&hCryptProv,
NULL,
NULL,
PROV_DH_SCHANNEL,
0))
{
//printf("A cryptographic provider has been acquired. \n");
}
else
{
throw("Error during CryptAcquireContext!error code=");
}
//--------------------------------------------------------------------
// Create the session key.
{
//--------------------------------------------------------------------
// The file will be encrypted with a session key derived from a
// password.
// The session key will be recreated when the file is decrypted
// only if the password used to create the key is available.
//--------------------------------------------------------------------
// Create a hash object.
if(CryptCreateHash(
hCryptProv,
CALG_MD5,
0,
0,
&hHash))
{
// printf("A hash object has been created. \n");
}
else
{
throw("Error during CryptCreateHash!\n");
}
//--------------------------------------------------------------------
// Hash the password.
if(CryptHashData(
hHash,
(BYTE *)szPassword,
(DWORD)strlen(szPassword),
0))
{
//printf("The password has been added to the hash. \n");
}
else
{
throw("Error during CryptHashData. \n");
}
//--------------------------------------------------------------------
// Derive a session key from the hash object.
if(CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey))
{
// printf("An encryption key is derived from the password hash. \n");
}
else
{
throw("Error during CryptDeriveKey!\n");
}
//--------------------------------------------------------------------
// Destroy the hash object.
CryptDestroyHash(hHash);
hHash = 0;
}
//--------------------------------------------------------------------
// The session key is now ready. If it is not a key derived from a
// password, the session key encrypted with the encrypter's private
// key has been written to the destination file.
//--------------------------------------------------------------------
// Determine number of bytes to encrypt at a time.
// This must be a multiple of ENCRYPT_BLOCK_SIZE.
// ENCRYPT_BLOCK_SIZE is set by a #define statement.
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
//--------------------------------------------------------------------
// Determine the block size. If a block cipher is used,
// it must have room for an extra block.
if(ENCRYPT_BLOCK_SIZE > 1)
dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
else
dwBufferLen = dwBlockLen;
//--------------------------------------------------------------------
// Allocate memory.
if(pbBuffer = (BYTE *)malloc(dwBufferLen))
{
// printf("Memory has been allocated for the buffer. \n");
}
else
{
throw("Out of memory. \n");
}
//put the password in the file
unsigned char passBuf[MAX_PASS_BUF];
ZeroMemory(passBuf,MAX_PASS_BUF);
int strLen = (DWORD)strlen(szPassword);
if( strLen > MAX_PASS_LEN)
{
throw("password is too long!\r\n");
//return FALSE;
}
dwCount = MAX_PASS_LEN;
strcpy((char*)passBuf,szPassword);
if(!CryptEncrypt(
hKey,
0,
TRUE,
0,
passBuf,
&dwCount,
MAX_PASS_BUF))
{
throw("Error during CryptEncrypt. \n");
}
ASSERT(dwCount == MAX_PASS_BUF);
fwrite(passBuf, 1, dwCount, hDestination);
//--------------------------------------------------------------------
// In a do loop, encrypt the source file and write to the source file.
do
{
//--------------------------------------------------------------------
// Read up to dwBlockLen bytes from the source file.
dwCount = (DWORD)fread(pbBuffer, 1, dwBlockLen, hSource);
if(ferror(hSource))
{
throw("Error reading plaintext!\n");
}
//--------------------------------------------------------------------
// Encrypt data.
if(!CryptEncrypt(
hKey,
0,
feof(hSource),
0,
pbBuffer,
&dwCount,
dwBufferLen))
{
throw("Error during CryptEncrypt. \n");
}
//--------------------------------------------------------------------
// Write data to the destination file.
fwrite(pbBuffer, 1, dwCount, hDestination);
if(ferror(hDestination))
{
throw("Error writing ciphertext.");
}
}
while(!feof(hSource));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -