1. 程式人生 > >C語言加密解密演算法

C語言加密解密演算法

本文介紹了英文字串的加密、解密過程。是根據網上一篇部落格的題目重寫的程式。

原文地址:http://blog.csdn.net/meditator_hkx/article/details/49445773

#include <stdio.h>
#include<string.h>

int AlphabetTransfer(char *Alphabet)
{
	char AlphabetBefore = *Alphabet;
	char AlphabetAfter = 0;
	
	char AlphabetSerialBefore = 0;
	char AlphabetSerialAfter = 0;
	
	if(AlphabetBefore >= 'a' && AlphabetBefore <= 'z')
		AlphabetSerialBefore = AlphabetBefore - 'a' + 1;

	if(AlphabetBefore >= 'A' && AlphabetBefore <= 'Z')
		AlphabetSerialBefore = AlphabetBefore - 'A' + 27;	
	
	if(AlphabetSerialBefore == 0)return 0;
	
	AlphabetSerialAfter = AlphabetSerialBefore * 3;
	
	if(AlphabetSerialAfter > 52)
		AlphabetSerialAfter = AlphabetSerialAfter % 52;

	if(AlphabetSerialAfter < 27)
		AlphabetAfter = 'a' + AlphabetSerialAfter - 1;

	if(AlphabetSerialAfter >= 27 && AlphabetSerialAfter < 53)
		AlphabetAfter = 'A' + AlphabetSerialAfter - 27;	
	
	*Alphabet = AlphabetAfter;
	
	return 1;
}

int AlphabetTransBack(char *Alphabet)
{
	char AlphabetBefore = *Alphabet;
	char AlphabetAfter = 0;
	
	char AlphabetSerialBefore = 0;
	char AlphabetSerialAfter = 0;
	
	if(AlphabetBefore >= 'a' && AlphabetBefore <= 'z')
		AlphabetSerialBefore = AlphabetBefore - 'a' + 1;

	if(AlphabetBefore >= 'A' && AlphabetBefore <= 'Z')
		AlphabetSerialBefore = AlphabetBefore - 'A' + 27;	
	
	if(AlphabetSerialBefore == 0)return 0;	

	if(AlphabetSerialBefore % 3 == 0)AlphabetSerialAfter = AlphabetSerialBefore / 3;
	else if((AlphabetSerialBefore + 52) % 3 == 0) AlphabetSerialAfter = (AlphabetSerialBefore + 52) / 3;
	else if((AlphabetSerialBefore + 104) % 3 == 0) AlphabetSerialAfter = (AlphabetSerialBefore + 104) / 3;
	else return 0;
	
	if(AlphabetSerialAfter < 27)
		AlphabetAfter = 'a' + AlphabetSerialAfter - 1;

	if(AlphabetSerialAfter >= 27 && AlphabetSerialAfter < 53)
		AlphabetAfter = 'A' + AlphabetSerialAfter - 27;	
	
	*Alphabet = AlphabetAfter;	
	
	return 1;
}

int StringTransfer(char *StringHead)
{
	char *PString = StringHead;
	
	while(*PString != '\0')
	{
		if(AlphabetTransfer(PString) == 0)return 0;
		PString++;
	}
	return 1;
}

int StringTransBack(char *StringHead)
{
	char *PString = StringHead;
	
	while(*PString != '\0')
	{
		if(AlphabetTransBack(PString) == 0)return 0;
		PString++;
	}
	return 1;
}

void main(void)
{
	char StringText[30] = "anknjiaingnmlkmangfnj";
	
	puts(StringText);

	getchar();
	
	StringTransfer(StringText);
	
	puts(StringText);
	
	getchar();
	
	StringTransBack(StringText);	

	puts(StringText);
	
	getchar();

	system("pause");
	
}