SlideShare a Scribd company logo
1 of 17
Download to read offline
File encryption. [32] Write a program which accepts a filename as a command-line argument [-
32]. It should then ask for a password via stdin (but it should not visible when entered; use
getpass for this) [4]. The program should encrypt the file using a block-cipher algorithm (see
encryption.rst for details) [12] if it was not already encrypted by the program, and rename it with
a .enc extension. If it was already encrypted, it should decrypt the file and remove the .enc
extension [12]. Under no circumstance should the program multiply encrypt the file [4]. Call the
program encrypt.cpp. here is encrypt.rst Suppose I have an input file to encrypt: .. raw: The only
true wisdom is in knowing you know nothing. (A quote by Socrates.) What I can do then is ask
the user for a password. Suppose the user enters kitties. Then what I may do is pre-pend the
password to an output file, and add kitties in rounds to the file: .. raw: kittiesThe only true
wisdom is in knowing you know nothing. + kittieskittieskittieskittieskittieskittieskittieskittieskit -
---------------------------------------------------------- =
fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd When I add the characters in the
string kitties, I get what appears to be jumbled garbage. Without the password, it is hard to
decrypt the file. To decrypt the file, I ask the user for the password. Suppose they enter bubbles
(the wrong password). .. raw: fhdkalhfioepwah... - bubbles ------------------ = ueiaqnv I see that
by subtracting bubbles off the encrypted text, I do not get the string bubbles back, so bubbles is
not the password. If the user enters kitties (the correct password): .. raw: fhdkalhfioepwah... -
kitties ------------------ = kitties Then I see that what I get back is kitties, and since it matches the
user password entered, I may proceed to decrypt the rest of the file simply by subtracting kitties
off it in rounds. .. raw: = fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd -
kittieskittieskittieskittieskittieskittieskittieskittieskit ------------------------------------------------------
----- kittiesThe only true wisdom is in knowing you know nothing. Thus I obtain the original
message. Notice the user-supplied password itself is a necessary element of the decryption. This
type of algorithm is called a block cipher algorithm.
Solution
// Encrypting_a_File.cpp : Defines the entry point for the console
// application.
//
#include
#include
#include
#include
#include
// Link with the Advapi32.lib file.
#pragma comment (lib, "advapi32")
#define KEYLENGTH 0x00800000
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
bool MyEncryptFile(
LPTSTR szSource,
LPTSTR szDestination,
LPTSTR szPassword);
void MyHandleError(
LPTSTR psz,
int nErrorNumber);
int _tmain(int argc, _TCHAR* argv[])
{
if(argc < 3)
{
_tprintf(TEXT("Usage: ")
TEXT(" |  "));
_tprintf(TEXT(" is optional. "));
_tprintf(TEXT("Press any key to exit."));
_gettch();
return 1;
}
LPTSTR pszSource = argv[1];
LPTSTR pszDestination = argv[2];
LPTSTR pszPassword = NULL;
if(argc >= 4)
{
pszPassword = argv[3];
}
//---------------------------------------------------------------
// Call EncryptFile to do the actual encryption.
if(MyEncryptFile(pszSource, pszDestination, pszPassword))
{
_tprintf(
TEXT("Encryption of the file %s was successful.  "),
pszSource);
_tprintf(
TEXT("The encrypted data is in file %s. "),
pszDestination);
}
else
{
MyHandleError(
TEXT("Error encrypting file! "),
GetLastError());
}
return 0;
}
//-------------------------------------------------------------------
// Code for the function MyEncryptFile called by main.
//-------------------------------------------------------------------
// Parameters passed are:
// pszSource, the name of the input, a plaintext file.
// pszDestination, the name of the output, an encrypted file to be
// created.
// pszPassword, either NULL if a password is not to be used or the
// string that is the password.
bool MyEncryptFile(
LPTSTR pszSourceFile,
LPTSTR pszDestinationFile,
LPTSTR pszPassword)
{
//---------------------------------------------------------------
// Declare and initialize local variables.
bool fReturn = false;
HANDLE hSourceFile = INVALID_HANDLE_VALUE;
HANDLE hDestinationFile = INVALID_HANDLE_VALUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = NULL;
HCRYPTKEY hXchgKey = NULL;
HCRYPTHASH hHash = NULL;
PBYTE pbKeyBlob = NULL;
DWORD dwKeyBlobLen;
PBYTE pbBuffer = NULL;
DWORD dwBlockLen;
DWORD dwBufferLen;
DWORD dwCount;
//---------------------------------------------------------------
// Open the source file.
hSourceFile = CreateFile(
pszSourceFile,
FILE_READ_DATA,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(INVALID_HANDLE_VALUE != hSourceFile)
{
_tprintf(
TEXT("The source plaintext file, %s, is open.  "),
pszSourceFile);
}
else
{
MyHandleError(
TEXT("Error opening source plaintext file! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// Open the destination file.
hDestinationFile = CreateFile(
pszDestinationFile,
FILE_WRITE_DATA,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(INVALID_HANDLE_VALUE != hDestinationFile)
{
_tprintf(
TEXT("The destination file, %s, is open.  "),
pszDestinationFile);
}
else
{
MyHandleError(
TEXT("Error opening destination file! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// Get the handle to the default provider.
if(CryptAcquireContext(
&hCryptProv,
NULL,
MS_ENHANCED_PROV,
PROV_RSA_FULL,
0))
{
_tprintf(
TEXT("A cryptographic provider has been acquired.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptAcquireContext! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// Create the session key.
if(!pszPassword || !pszPassword[0])
{
//-----------------------------------------------------------
// No password was passed.
// Encrypt the file with a random session key, and write the
// key to a file.
//-----------------------------------------------------------
// Create a random session key.
if(CryptGenKey(
hCryptProv,
ENCRYPT_ALGORITHM,
KEYLENGTH | CRYPT_EXPORTABLE,
&hKey))
{
_tprintf(TEXT("A session key has been created.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptGenKey.  "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Get the handle to the exchange public key.
if(CryptGetUserKey(
hCryptProv,
AT_KEYEXCHANGE,
&hXchgKey))
{
_tprintf(
TEXT("The user public key has been retrieved.  "));
}
else
{
if(NTE_NO_KEY == GetLastError())
{
// No exchange key exists. Try to create one.
if(!CryptGenKey(
hCryptProv,
AT_KEYEXCHANGE,
CRYPT_EXPORTABLE,
&hXchgKey))
{
MyHandleError(
TEXT("Could not create "
"a user public key. "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
else
{
MyHandleError(
TEXT("User public key is not available and may ")
TEXT("not exist. "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
//-----------------------------------------------------------
// Determine size of the key BLOB, and allocate memory.
if(CryptExportKey(
hKey,
hXchgKey,
SIMPLEBLOB,
0,
NULL,
&dwKeyBlobLen))
{
_tprintf(
TEXT("The key BLOB is %d bytes long.  "),
dwKeyBlobLen);
}
else
{
MyHandleError(
TEXT("Error computing BLOB length!  "),
GetLastError());
goto Exit_MyEncryptFile;
}
if(pbKeyBlob = (BYTE *)malloc(dwKeyBlobLen))
{
_tprintf(
TEXT("Memory is allocated for the key BLOB.  "));
}
else
{
MyHandleError(TEXT("Out of memory.  "), E_OUTOFMEMORY);
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Encrypt and export the session key into a simple key
// BLOB.
if(CryptExportKey(
hKey,
hXchgKey,
SIMPLEBLOB,
0,
pbKeyBlob,
&dwKeyBlobLen))
{
_tprintf(TEXT("The key has been exported.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptExportKey! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Release the key exchange key handle.
if(hXchgKey)
{
if(!(CryptDestroyKey(hXchgKey)))
{
MyHandleError(
TEXT("Error during CryptDestroyKey. "),
GetLastError());
goto Exit_MyEncryptFile;
}
hXchgKey = 0;
}
//-----------------------------------------------------------
// Write the size of the key BLOB to the destination file.
if(!WriteFile(
hDestinationFile,
&dwKeyBlobLen,
sizeof(DWORD),
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error writing header. "),
GetLastError());
goto Exit_MyEncryptFile;
}
else
{
_tprintf(TEXT("A file header has been written.  "));
}
//-----------------------------------------------------------
// Write the key BLOB to the destination file.
if(!WriteFile(
hDestinationFile,
pbKeyBlob,
dwKeyBlobLen,
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error writing header. "),
GetLastError());
goto Exit_MyEncryptFile;
}
else
{
_tprintf(
TEXT("The key BLOB has been written to the ")
TEXT("file.  "));
}
// Free memory.
free(pbKeyBlob);
}
else
{
//-----------------------------------------------------------
// 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))
{
_tprintf(TEXT("A hash object has been created.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptCreateHash! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Hash the password.
if(CryptHashData(
hHash,
(BYTE *)pszPassword,
lstrlen(pszPassword),
0))
{
_tprintf(
TEXT("The password has been added to the hash.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptHashData.  "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Derive a session key from the hash object.
if(CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey))
{
_tprintf(
TEXT("An encryption key is derived from the ")
TEXT("password hash.  "));
}
else
{
MyHandleError(
TEXT("Error during CryptDeriveKey! "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
//---------------------------------------------------------------
// The session key is now ready. If it is not a key derived from
// a password, the session key encrypted with the private key
// has been written to the destination file.
//---------------------------------------------------------------
// Determine the 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))
{
_tprintf(
TEXT("Memory has been allocated for the buffer.  "));
}
else
{
MyHandleError(TEXT("Out of memory.  "), E_OUTOFMEMORY);
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// In a do loop, encrypt the source file,
// and write to the source file.
bool fEOF = FALSE;
do
{
//-----------------------------------------------------------
// Read up to dwBlockLen bytes from the source file.
if(!ReadFile(
hSourceFile,
pbBuffer,
dwBlockLen,
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error reading plaintext! "),
GetLastError());
goto Exit_MyEncryptFile;
}
if(dwCount < dwBlockLen)
{
fEOF = TRUE;
}
//-----------------------------------------------------------
// Encrypt data.
if(!CryptEncrypt(
hKey,
NULL,
fEOF,
0,
pbBuffer,
&dwCount,
dwBufferLen))
{
MyHandleError(
TEXT("Error during CryptEncrypt.  "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Write the encrypted data to the destination file.
if(!WriteFile(
hDestinationFile,
pbBuffer,
dwCount,
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error writing ciphertext. "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// End the do loop when the last block of the source file
// has been read, encrypted, and written to the destination
// file.
} while(!fEOF);
fReturn = true;
Exit_MyEncryptFile:
//---------------------------------------------------------------
// Close files.
if(hSourceFile)
{
CloseHandle(hSourceFile);
}
if(hDestinationFile)
{
CloseHandle(hDestinationFile);
}
//---------------------------------------------------------------
// Free memory.
if(pbBuffer)
{
free(pbBuffer);
}
//-----------------------------------------------------------
// Release the hash object.
if(hHash)
{
if(!(CryptDestroyHash(hHash)))
{
MyHandleError(
TEXT("Error during CryptDestroyHash. "),
GetLastError());
}
hHash = NULL;
}
//---------------------------------------------------------------
// Release the session key.
if(hKey)
{
if(!(CryptDestroyKey(hKey)))
{
MyHandleError(
TEXT("Error during CryptDestroyKey! "),
GetLastError());
}
}
//---------------------------------------------------------------
// Release the provider handle.
if(hCryptProv)
{
if(!(CryptReleaseContext(hCryptProv, 0)))
{
MyHandleError(
TEXT("Error during CryptReleaseContext! "),
GetLastError());
}
}
return fReturn;
} // End Encryptfile.
//-------------------------------------------------------------------
// This example uses the function MyHandleError, 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 MyHandleError(LPTSTR psz, int nErrorNumber)
{
_ftprintf(stderr, TEXT("An error occurred in the program.  "));
_ftprintf(stderr, TEXT("%s "), psz);
_ftprintf(stderr, TEXT("Error number %x. "), nErrorNumber);
}

More Related Content

Similar to File encryption. [32] Write a program which accepts a filename as a .pdf

Linux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene PirogovLinux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene PirogovPivorak MeetUp
 
Beyond Golden Containers: Complementing Docker with Puppet
Beyond Golden Containers: Complementing Docker with PuppetBeyond Golden Containers: Complementing Docker with Puppet
Beyond Golden Containers: Complementing Docker with Puppetlutter
 
Postgresql 12 streaming replication hol
Postgresql 12 streaming replication holPostgresql 12 streaming replication hol
Postgresql 12 streaming replication holVijay Kumar N
 
Passbolt Introduction and Usage for secret managment
Passbolt Introduction and Usage for secret managmentPassbolt Introduction and Usage for secret managment
Passbolt Introduction and Usage for secret managmentThierry Gayet
 
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...Andrew Case
 
Virtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetVirtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetOmar Reygaert
 
Need help implementing the skeleton code below, I have provided the .pdf
Need help implementing the skeleton code below, I have provided the .pdfNeed help implementing the skeleton code below, I have provided the .pdf
Need help implementing the skeleton code below, I have provided the .pdfezzi552
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersYury Chemerkin
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - RoutersLogicaltrust pl
 
Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014Puppet
 
Spraykatz installation & basic usage
Spraykatz installation & basic usageSpraykatz installation & basic usage
Spraykatz installation & basic usageSylvain Cortes
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docxwkyra78
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnSandro Zaccarini
 
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bChereCheek752
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Ilya Haykinson
 
Character_Device_drvier_pc
Character_Device_drvier_pcCharacter_Device_drvier_pc
Character_Device_drvier_pcRashila Rr
 

Similar to File encryption. [32] Write a program which accepts a filename as a .pdf (20)

Linux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene PirogovLinux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene Pirogov
 
Cryptography Attacks and Applications
Cryptography Attacks and ApplicationsCryptography Attacks and Applications
Cryptography Attacks and Applications
 
Beyond Golden Containers: Complementing Docker with Puppet
Beyond Golden Containers: Complementing Docker with PuppetBeyond Golden Containers: Complementing Docker with Puppet
Beyond Golden Containers: Complementing Docker with Puppet
 
Computer Security
Computer SecurityComputer Security
Computer Security
 
Postgresql 12 streaming replication hol
Postgresql 12 streaming replication holPostgresql 12 streaming replication hol
Postgresql 12 streaming replication hol
 
Passbolt Introduction and Usage for secret managment
Passbolt Introduction and Usage for secret managmentPassbolt Introduction and Usage for secret managment
Passbolt Introduction and Usage for secret managment
 
Hta w22
Hta w22Hta w22
Hta w22
 
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...
Memory Forensics: Defeating Disk Encryption, Skilled Attackers, and Advanced ...
 
Virtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetVirtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + Puppet
 
Need help implementing the skeleton code below, I have provided the .pdf
Need help implementing the skeleton code below, I have provided the .pdfNeed help implementing the skeleton code below, I have provided the .pdf
Need help implementing the skeleton code below, I have provided the .pdf
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routers
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - Routers
 
Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014
 
unixtoolbox
unixtoolboxunixtoolbox
unixtoolbox
 
Spraykatz installation & basic usage
Spraykatz installation & basic usageSpraykatz installation & basic usage
Spraykatz installation & basic usage
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vuln
 
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
 
Character_Device_drvier_pc
Character_Device_drvier_pcCharacter_Device_drvier_pc
Character_Device_drvier_pc
 

More from jyothimuppasani1

How does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfHow does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfjyothimuppasani1
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfjyothimuppasani1
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfjyothimuppasani1
 
For each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfFor each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfjyothimuppasani1
 
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfFind an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfjyothimuppasani1
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfjyothimuppasani1
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfjyothimuppasani1
 
Did colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfDid colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfjyothimuppasani1
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfjyothimuppasani1
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfjyothimuppasani1
 
Considering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfConsidering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfjyothimuppasani1
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfjyothimuppasani1
 
Conceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfConceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfjyothimuppasani1
 
A variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfA variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfjyothimuppasani1
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdfjyothimuppasani1
 
You are to write a GUI program that will allow a user to buy, sell a.pdf
You are to write a GUI program that will allow a user to buy, sell a.pdfYou are to write a GUI program that will allow a user to buy, sell a.pdf
You are to write a GUI program that will allow a user to buy, sell a.pdfjyothimuppasani1
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfjyothimuppasani1
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfjyothimuppasani1
 

More from jyothimuppasani1 (20)

How does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfHow does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdf
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
 
For each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfFor each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdf
 
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfFind an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdf
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdf
 
Did colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfDid colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdf
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdf
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdf
 
Considering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfConsidering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdf
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
 
Conceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfConceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdf
 
A variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfA variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdf
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
You are to write a GUI program that will allow a user to buy, sell a.pdf
You are to write a GUI program that will allow a user to buy, sell a.pdfYou are to write a GUI program that will allow a user to buy, sell a.pdf
You are to write a GUI program that will allow a user to buy, sell a.pdf
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdf
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdf
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 

File encryption. [32] Write a program which accepts a filename as a .pdf

  • 1. File encryption. [32] Write a program which accepts a filename as a command-line argument [- 32]. It should then ask for a password via stdin (but it should not visible when entered; use getpass for this) [4]. The program should encrypt the file using a block-cipher algorithm (see encryption.rst for details) [12] if it was not already encrypted by the program, and rename it with a .enc extension. If it was already encrypted, it should decrypt the file and remove the .enc extension [12]. Under no circumstance should the program multiply encrypt the file [4]. Call the program encrypt.cpp. here is encrypt.rst Suppose I have an input file to encrypt: .. raw: The only true wisdom is in knowing you know nothing. (A quote by Socrates.) What I can do then is ask the user for a password. Suppose the user enters kitties. Then what I may do is pre-pend the password to an output file, and add kitties in rounds to the file: .. raw: kittiesThe only true wisdom is in knowing you know nothing. + kittieskittieskittieskittieskittieskittieskittieskittieskit - ---------------------------------------------------------- = fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd When I add the characters in the string kitties, I get what appears to be jumbled garbage. Without the password, it is hard to decrypt the file. To decrypt the file, I ask the user for the password. Suppose they enter bubbles (the wrong password). .. raw: fhdkalhfioepwah... - bubbles ------------------ = ueiaqnv I see that by subtracting bubbles off the encrypted text, I do not get the string bubbles back, so bubbles is not the password. If the user enters kitties (the correct password): .. raw: fhdkalhfioepwah... - kitties ------------------ = kitties Then I see that what I get back is kitties, and since it matches the user password entered, I may proceed to decrypt the rest of the file simply by subtracting kitties off it in rounds. .. raw: = fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd - kittieskittieskittieskittieskittieskittieskittieskittieskit ------------------------------------------------------ ----- kittiesThe only true wisdom is in knowing you know nothing. Thus I obtain the original message. Notice the user-supplied password itself is a necessary element of the decryption. This type of algorithm is called a block cipher algorithm. Solution // Encrypting_a_File.cpp : Defines the entry point for the console // application. // #include #include #include #include
  • 2. #include // Link with the Advapi32.lib file. #pragma comment (lib, "advapi32") #define KEYLENGTH 0x00800000 #define ENCRYPT_ALGORITHM CALG_RC4 #define ENCRYPT_BLOCK_SIZE 8 bool MyEncryptFile( LPTSTR szSource, LPTSTR szDestination, LPTSTR szPassword); void MyHandleError( LPTSTR psz, int nErrorNumber); int _tmain(int argc, _TCHAR* argv[]) { if(argc < 3) { _tprintf(TEXT("Usage: ") TEXT(" | ")); _tprintf(TEXT(" is optional. ")); _tprintf(TEXT("Press any key to exit.")); _gettch(); return 1; } LPTSTR pszSource = argv[1]; LPTSTR pszDestination = argv[2]; LPTSTR pszPassword = NULL; if(argc >= 4) { pszPassword = argv[3]; } //--------------------------------------------------------------- // Call EncryptFile to do the actual encryption. if(MyEncryptFile(pszSource, pszDestination, pszPassword)) { _tprintf(
  • 3. TEXT("Encryption of the file %s was successful. "), pszSource); _tprintf( TEXT("The encrypted data is in file %s. "), pszDestination); } else { MyHandleError( TEXT("Error encrypting file! "), GetLastError()); } return 0; } //------------------------------------------------------------------- // Code for the function MyEncryptFile called by main. //------------------------------------------------------------------- // Parameters passed are: // pszSource, the name of the input, a plaintext file. // pszDestination, the name of the output, an encrypted file to be // created. // pszPassword, either NULL if a password is not to be used or the // string that is the password. bool MyEncryptFile( LPTSTR pszSourceFile, LPTSTR pszDestinationFile, LPTSTR pszPassword) { //--------------------------------------------------------------- // Declare and initialize local variables. bool fReturn = false; HANDLE hSourceFile = INVALID_HANDLE_VALUE; HANDLE hDestinationFile = INVALID_HANDLE_VALUE; HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKey = NULL; HCRYPTKEY hXchgKey = NULL;
  • 4. HCRYPTHASH hHash = NULL; PBYTE pbKeyBlob = NULL; DWORD dwKeyBlobLen; PBYTE pbBuffer = NULL; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; //--------------------------------------------------------------- // Open the source file. hSourceFile = CreateFile( pszSourceFile, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE != hSourceFile) { _tprintf( TEXT("The source plaintext file, %s, is open. "), pszSourceFile); } else { MyHandleError( TEXT("Error opening source plaintext file! "), GetLastError()); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // Open the destination file. hDestinationFile = CreateFile( pszDestinationFile, FILE_WRITE_DATA,
  • 5. FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE != hDestinationFile) { _tprintf( TEXT("The destination file, %s, is open. "), pszDestinationFile); } else { MyHandleError( TEXT("Error opening destination file! "), GetLastError()); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // Get the handle to the default provider. if(CryptAcquireContext( &hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0)) { _tprintf( TEXT("A cryptographic provider has been acquired. ")); } else { MyHandleError( TEXT("Error during CryptAcquireContext! "), GetLastError()); goto Exit_MyEncryptFile;
  • 6. } //--------------------------------------------------------------- // Create the session key. if(!pszPassword || !pszPassword[0]) { //----------------------------------------------------------- // No password was passed. // Encrypt the file with a random session key, and write the // key to a file. //----------------------------------------------------------- // Create a random session key. if(CryptGenKey( hCryptProv, ENCRYPT_ALGORITHM, KEYLENGTH | CRYPT_EXPORTABLE, &hKey)) { _tprintf(TEXT("A session key has been created. ")); } else { MyHandleError( TEXT("Error during CryptGenKey. "), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Get the handle to the exchange public key. if(CryptGetUserKey( hCryptProv, AT_KEYEXCHANGE, &hXchgKey)) { _tprintf( TEXT("The user public key has been retrieved. ")); }
  • 7. else { if(NTE_NO_KEY == GetLastError()) { // No exchange key exists. Try to create one. if(!CryptGenKey( hCryptProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hXchgKey)) { MyHandleError( TEXT("Could not create " "a user public key. "), GetLastError()); goto Exit_MyEncryptFile; } } else { MyHandleError( TEXT("User public key is not available and may ") TEXT("not exist. "), GetLastError()); goto Exit_MyEncryptFile; } } //----------------------------------------------------------- // Determine size of the key BLOB, and allocate memory. if(CryptExportKey( hKey, hXchgKey, SIMPLEBLOB, 0, NULL, &dwKeyBlobLen))
  • 8. { _tprintf( TEXT("The key BLOB is %d bytes long. "), dwKeyBlobLen); } else { MyHandleError( TEXT("Error computing BLOB length! "), GetLastError()); goto Exit_MyEncryptFile; } if(pbKeyBlob = (BYTE *)malloc(dwKeyBlobLen)) { _tprintf( TEXT("Memory is allocated for the key BLOB. ")); } else { MyHandleError(TEXT("Out of memory. "), E_OUTOFMEMORY); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Encrypt and export the session key into a simple key // BLOB. if(CryptExportKey( hKey, hXchgKey, SIMPLEBLOB, 0, pbKeyBlob, &dwKeyBlobLen)) { _tprintf(TEXT("The key has been exported. ")); } else
  • 9. { MyHandleError( TEXT("Error during CryptExportKey! "), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Release the key exchange key handle. if(hXchgKey) { if(!(CryptDestroyKey(hXchgKey))) { MyHandleError( TEXT("Error during CryptDestroyKey. "), GetLastError()); goto Exit_MyEncryptFile; } hXchgKey = 0; } //----------------------------------------------------------- // Write the size of the key BLOB to the destination file. if(!WriteFile( hDestinationFile, &dwKeyBlobLen, sizeof(DWORD), &dwCount, NULL)) { MyHandleError( TEXT("Error writing header. "), GetLastError()); goto Exit_MyEncryptFile; }
  • 10. else { _tprintf(TEXT("A file header has been written. ")); } //----------------------------------------------------------- // Write the key BLOB to the destination file. if(!WriteFile( hDestinationFile, pbKeyBlob, dwKeyBlobLen, &dwCount, NULL)) { MyHandleError( TEXT("Error writing header. "), GetLastError()); goto Exit_MyEncryptFile; } else { _tprintf( TEXT("The key BLOB has been written to the ") TEXT("file. ")); } // Free memory. free(pbKeyBlob); } else { //----------------------------------------------------------- // 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. //-----------------------------------------------------------
  • 11. // Create a hash object. if(CryptCreateHash( hCryptProv, CALG_MD5, 0, 0, &hHash)) { _tprintf(TEXT("A hash object has been created. ")); } else { MyHandleError( TEXT("Error during CryptCreateHash! "), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Hash the password. if(CryptHashData( hHash, (BYTE *)pszPassword, lstrlen(pszPassword), 0)) { _tprintf( TEXT("The password has been added to the hash. ")); } else { MyHandleError( TEXT("Error during CryptHashData. "), GetLastError()); goto Exit_MyEncryptFile; } //-----------------------------------------------------------
  • 12. // Derive a session key from the hash object. if(CryptDeriveKey( hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { _tprintf( TEXT("An encryption key is derived from the ") TEXT("password hash. ")); } else { MyHandleError( TEXT("Error during CryptDeriveKey! "), GetLastError()); goto Exit_MyEncryptFile; } } //--------------------------------------------------------------- // The session key is now ready. If it is not a key derived from // a password, the session key encrypted with the private key // has been written to the destination file. //--------------------------------------------------------------- // Determine the 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;
  • 13. } else { dwBufferLen = dwBlockLen; } //--------------------------------------------------------------- // Allocate memory. if(pbBuffer = (BYTE *)malloc(dwBufferLen)) { _tprintf( TEXT("Memory has been allocated for the buffer. ")); } else { MyHandleError(TEXT("Out of memory. "), E_OUTOFMEMORY); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // In a do loop, encrypt the source file, // and write to the source file. bool fEOF = FALSE; do { //----------------------------------------------------------- // Read up to dwBlockLen bytes from the source file. if(!ReadFile( hSourceFile, pbBuffer, dwBlockLen, &dwCount, NULL)) { MyHandleError( TEXT("Error reading plaintext! "), GetLastError());
  • 14. goto Exit_MyEncryptFile; } if(dwCount < dwBlockLen) { fEOF = TRUE; } //----------------------------------------------------------- // Encrypt data. if(!CryptEncrypt( hKey, NULL, fEOF, 0, pbBuffer, &dwCount, dwBufferLen)) { MyHandleError( TEXT("Error during CryptEncrypt. "), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Write the encrypted data to the destination file. if(!WriteFile( hDestinationFile, pbBuffer, dwCount, &dwCount, NULL)) { MyHandleError( TEXT("Error writing ciphertext. "), GetLastError()); goto Exit_MyEncryptFile; }
  • 15. //----------------------------------------------------------- // End the do loop when the last block of the source file // has been read, encrypted, and written to the destination // file. } while(!fEOF); fReturn = true; Exit_MyEncryptFile: //--------------------------------------------------------------- // Close files. if(hSourceFile) { CloseHandle(hSourceFile); } if(hDestinationFile) { CloseHandle(hDestinationFile); } //--------------------------------------------------------------- // Free memory. if(pbBuffer) { free(pbBuffer); } //----------------------------------------------------------- // Release the hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError( TEXT("Error during CryptDestroyHash. "), GetLastError()); } hHash = NULL; }
  • 16. //--------------------------------------------------------------- // Release the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError( TEXT("Error during CryptDestroyKey! "), GetLastError()); } } //--------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError( TEXT("Error during CryptReleaseContext! "), GetLastError()); } } return fReturn; } // End Encryptfile. //------------------------------------------------------------------- // This example uses the function MyHandleError, 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 MyHandleError(LPTSTR psz, int nErrorNumber) { _ftprintf(stderr, TEXT("An error occurred in the program. ")); _ftprintf(stderr, TEXT("%s "), psz);
  • 17. _ftprintf(stderr, TEXT("Error number %x. "), nErrorNumber); }