Simple implementation of file encryption (C language)

Source: Internet
Author: User
Requirement: encrypt the file in DWORD units, and write each DWORD and 0xfcba0000 to another file.

Answer: # include <stdio. h>
# Include <stdlib. h>

# Define DWORD unsigned long
# Define BYTE unsigned char
# Define false 0
# Define true 1

Int main (int argc, char * argv [])
{
FILE * hSource;
FILE * hDestination;

DWORD dwKey = 0xfcba0000;

Char * pbBuffer;
DWORD dwBufferLen = sizeof (DWORD );
DWORD dwCount;
DWORD dwData;

If (argv [1] = 0 | argv [2] = 0)
{
Printf ("missing argument! \ N ");
Return false;
}
Char * szSource = argv [1];
Char * szDestination = argv [2];
 
HSource = fopen (szSource, "rb"); // open the source file.
HDestination = fopen (szDestination, "wb"); // open the target file

If (hSource = NULL) {printf ("open Source File error! "); Return false ;}
If (hDestination = NULL) {printf ("open Destination File error! "); Return false ;}

// Allocate a buffer
PbBuffer = (char *) malloc (dwBufferLen );

Do {
// Read dwBlockLen bytes from the source file
DwCount = fread (pbBuffer, 1, dwBufferLen, hSource );
// Encrypt data
DwData = * (DWORD *) pbBuffer; // char * TO dword
DwData ^ = dwKey; // xor operation
PbBuffer = (char *) & dwData;
// Write encrypted data to the target file
Fwrite (pbBuffer, 1, dwCount, hDestination );
} While (! Feof (hSource ));
 
// Close the file and release the memory
Fclose (hSource );
Fclose (hDestination );

Printf ("% s is encrypted to % s \ n", szSource, szDestination );
Return 0;
}

TIPS:
Char * To DWORD: dwData = * (DWORD *) pbBuffer;
DWORD to char *: pbBuffer = (char *) & dwData;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.