1. 程式人生 > >字串加解密

字串加解密

本題在解題時分開考慮加密和解密;對於加密可以採用加密表的形式,即把明文對應的密碼錶寫出來,這樣加密只是簡單的查表過程,速率很快的;

對於解密同樣採取把解密表寫出來,解密就是簡單的查表即可

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


#define M 200
void Encrypt(char aucPassword[], char aucResult[])
{
	char encrypt_book_table[26] = {0};
	char encrypt_book_number[10] = { '1','2','3','4','5','6','7','8','9','0' };
	int i;
	int length_aucPassword = 0;

	//初始化字母加密表
	for (i = 0; i < 25; i++)
	{
		encrypt_book_table[i] = 'A' + i + 1;
	}
	encrypt_book_table[25] = 'A';


	//加密過程
	length_aucPassword = strlen(aucPassword);
	for (i = 0; i < length_aucPassword; i++)
	{
		if (aucPassword[i] >= 'a' && aucPassword[i] <= 'z')
		{
			aucResult[i] = encrypt_book_table[aucPassword[i] - 'a'];
			
		}
		else if (aucPassword[i] >= 'A' && aucPassword[i] <= 'Z')
		{
			aucResult[i] = encrypt_book_table[aucPassword[i] - 'A'] + 32;
		}
		else if (aucPassword[i] >='0' && aucPassword[i] <= '9')
		{
			aucResult[i] = encrypt_book_number[aucPassword[i] - '0'];
		}
		else
		{
			aucResult[i] = aucPassword[i];
		}
	}
	aucResult[i] = '\0';
	puts(aucResult);
}

int unEncrypt(char result[], char password[])
{
	char unencrypt_book_table[26] = {'Z'};
	char unencrypt_book_number[10] = { '9','0','1','2','3','4','5','6','7','8' };
	int i;
	int length_result = 0;
	char encrypt_aucPassword[M] = { 0 };

	for (i = 1; i < 26; i++)
	{
		unencrypt_book_table[i] = 'A' + i - 1;
	}


	//解密過程
	length_result = strlen(result);
	for (i = 0; i < length_result; i++)
	{
		if (result[i] >= 'a' && result[i] <= 'z')
		{
			password[i] = unencrypt_book_table[result[i] - 'a'];

		}
		else if (result[i] >= 'A' && result[i] <= 'Z')
		{
			password[i] = unencrypt_book_table[result[i] - 'A'] + 32;
		}
		else if (result[i] >= '0' && result[i] <= '9')
		{
			password[i] = unencrypt_book_number[result[i] - '0'];
		}
		else
		{
			password[i] = result[i];
		}
	}

	password[i] = '\0';
	puts(password);
}

void main(void)
{
	char aucPassword[M] = "abcdefg  .,ASDAFAF/;'p[123456789";
	char aucResult[M] = { 0 };
	char result[M] = "BCDEFGH   .,btebgbg/;'Q[234567890";
	char password[M] = { 0 };

	Encrypt(aucPassword, aucResult);

	unEncrypt(result, password);
}