SlideShare a Scribd company logo
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 Pirogov
Pivorak MeetUp
 
Cryptography Attacks and Applications
Cryptography Attacks and ApplicationsCryptography Attacks and Applications
Cryptography Attacks and Applications
UTD Computer Security Group
 
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
lutter
 
Postgresql 12 streaming replication hol
Postgresql 12 streaming replication holPostgresql 12 streaming replication hol
Postgresql 12 streaming replication hol
Vijay 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 managment
Thierry 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 .pdf
ezzi552
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - RoutersLogicaltrust pl
 
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
 
Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014Test-Driven Puppet Development - PuppetConf 2014
Test-Driven Puppet Development - PuppetConf 2014
Puppet
 
Spraykatz installation & basic usage
Spraykatz installation & basic usageSpraykatz installation & basic usage
Spraykatz installation & basic usage
Sylvain 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.docx
wkyra78
 
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
Sandro Zaccarini
 
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
ChereCheek752
 
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
Ilya 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
 
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 ...
 
Hta w22
Hta w22Hta w22
Hta w22
 
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
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - Routers
 
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
 
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.pdf
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
•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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 
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
jyothimuppasani1
 

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

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 

Recently uploaded (20)

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 

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); }