www.pudn.com > CipherSystem.rar > DESCipherSystem.cpp


#include "stdafx.h" 
#include "DESCipherSystem.h" 
 
void DESCipherSystem::PC_2(const binary_stream& keyStreamC28bit, const binary_stream& keyStreamD28bit, int displace) 
{ 
	int i; 
	binary_stream temp56bit = keyStreamC28bit; 
	for (i=0; i<(int)keyStreamD28bit.size(); i++) temp56bit.push_back(keyStreamD28bit[i]); 
 
	subKeyStream48bit[displace].clear(); 
	for (i=0; i<48; i++)  
	{ 
		subKeyStream48bit[displace].push_back((temp56bit[PC_2_BOX[i] - 1])); 
	} 
} 
 
void DESCipherSystem::CycleLeftShift(binary_stream& keyStreamC28bit, binary_stream& keyStreamD28bit, int round) 
{ 
	int cycleNum; 
	switch (round) 
	{ 
	case 1: 
	case 2: 
	case 9: 
	case 16: cycleNum = 1; break; 
	default: cycleNum = 2; 
	} 
	int i; 
	for (i=0; i> j)) result.push_back(true); 
			else result.push_back(false); 
		} 
	} 
	return result; 
} 
 
binary_stream DESCipherSystem::Expand(const binary_stream& BinaryStream32bit) 
{ 
	binary_stream temp48bit; 
	temp48bit.push_back(BinaryStream32bit[31]); 
	int i; 
	for (i=0; i<32; i++) 
	{ 
		temp48bit.push_back(BinaryStream32bit[i]); 
		if ((i % 4 == 0) && i != 0) 
		{ 
			temp48bit.push_back(BinaryStream32bit[i - 1]); 
			temp48bit.push_back(BinaryStream32bit[i]); 
		} 
	} 
	temp48bit.push_back(BinaryStream32bit[0]); 
	return temp48bit; 
} 
 
binary_stream DESCipherSystem::Ffunction(const binary_stream& BinaryStream32bit , int displace) 
{ 
	binary_stream temp48bit = Expand(BinaryStream32bit); 
	int i; 
	for (i=0; i<48; i++) temp48bit[i] ^= this->subKeyStream48bit[displace][i]; 
	return PboxPermutation(SboxPermutation(temp48bit)); 
} 
 
binary_stream DESCipherSystem::ProductSwitch(const binary_stream& BinaryStream64bit, 
										const binary_stream& keyStream64bit, int mark) 
{ 
	binary_stream leftStream32bit, 
		   rightStream32bit, 
		   leftStream32bitLater, 
		   rightStream32bitLater; 
 
	int i; 
	for (i=0; i<32; i++) leftStream32bit.push_back(BinaryStream64bit[i]); 
	for (; i<64; i++) rightStream32bit.push_back(BinaryStream64bit[i]); 
 
	SubKeyCreation(keyStream64bit); 
	for (i=0; i<16; i++) 
	{ 
		leftStream32bitLater = rightStream32bit; 
		if (mark == 1) rightStream32bitLater = Ffunction(rightStream32bit, i);   // Encrypt 
		else rightStream32bitLater = Ffunction(rightStream32bit, 15 - i);		 // Decrypt 
		int j; 
		for (j=0; j<32; j++) rightStream32bitLater[j] ^= leftStream32bit[j]; 
		leftStream32bit = leftStream32bitLater; 
		rightStream32bit = rightStream32bitLater; 
	} 
	for (i=0; i<32; i++) rightStream32bit.push_back(leftStream32bit[i]); 
	return rightStream32bit; 
} 
 
void DESCipherSystem::GetData(const string& input) 
{ 
	text = input; 
	int left = (int)text.length() % 8;             //确保输入是8的倍数 
	int i; 
	if (left != 0) left = 8 - left; 
	for (i=0; i