decrypt.c

来自「本人基于William Stalling的《密码学与网络安全》实现的128位DE」· C语言 代码 · 共 108 行

C
108
字号
//////////////////////////////////////////////////////////////////////////////
//						**************************							//
//						*Data Encryption Standard*							//
//						**************************							//
//																			//
//								Realized in C								//
//																			//
//								*************								//
//								*Constructed*								//
//								*     By    *								//
//								*           *								//
//								*Xie Xingwei*								//
//								*************								//
//																			//
//	If you have any question about my code,contact me with E-mail please	//
//																			//
//						xiexingwei_2008@hotmail.com							//
//////////////////////////////////////////////////////////////////////////////

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <stdio.h>
#include "key_gen.h"
#include "des.h"
#include "data_struct.h"

int main()
{
	int pfh,cfh;  /*Handle of the file "decryption" and "ciphertext"*/
	unsigned char Lbuffer[1000];/*Buffer for plaintext storage*/
	unsigned char Lresult[1000];/*Buffer for ciphertext storage*/
	unsigned char buffer[8];/*Buffer for DES input*/
	int i,x;

	if(key_gen())
	{
		perror("Problem in generating subkeys");
	}

	/* Open file for input: */
	if( (cfh = _open( "ciphertext", _O_RDONLY )) == -1 )
	{
		perror( "Can not open the file \"ciphertext\" " );
		_close( cfh );
		return 1;
	}

	/* Read in input: */
	if( ( _read( cfh, Lbuffer, 1000 ) ) <= 0 )
	{
		perror( "Problem reading file" );
		_close( cfh );
		return 1;
	}

	/*Create decryption file*/
	pfh=_creat( "decryption", _S_IREAD | _S_IWRITE );
	if( pfh == -1 )
	{
		perror( "Couldn't create decryption file" );
		_close( pfh );
	}
	
	while(Lbuffer[0]!='\0')
	{
		for(i=0;i<125;i++)
		{
			for(x=0;x<8;x++)
			{
				buffer[x]=Lbuffer[i*8+x];
			}
			if(des(buffer))
			{
				perror( "Problem decrypting data" );
				return 1;
			}

			for(x=0;x<8;x++)
			{
				Lresult[i*8+x]=buffer[x];
			}
		}

		/*Write data to decryption file*/
		if((_write( pfh, Lresult, 1000 ) )==-1)
		{
			perror( "Failed when wrote data to buffer" );
			_close(pfh);
		}

		/*Make the Lbuffer clean*/
		for(i=0;i<1000;i++)
		{
			Lbuffer[i]='\0';
		}

		/* Read in input: */
		_read( cfh, Lbuffer, 1000 );

	}

	_close(pfh);
	_close(cfh);

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?