using System;
using static System.Console;
namespace Test
{
class Program
{
//凯撒密码
static string table = "abcdefghijklmnopqrstuvwxyz";
//如果密码本没找到会丢失一位 相同偏移量 解密对不上 加密也不是预想的结果
//必须保证所有的都能找到 你要加密 解密的 所有字符都有对应
const int key = 3;
static string clearText = "unity";//明文
static string cipherText = "xqlwb";//暗文
static void Main(string[] args)
{
string tempCipher = Encrypt(table,clearText,key);
WriteLine(tempCipher);//xqlwb
string tempClear = Decode(table,cipherText,key);
WriteLine(tempClear);//unity
}
/// <summary>
/// 加密
/// </summary>
/// <param name="table">密码本</param>
/// <param name="text">明文</param>
/// <param name="key">偏移量</param>
static string Encrypt(string table,string text,int key)
{
string cipherText = "";
for (int i = 0; i < text.Length; i++)
{
int index = table.IndexOf(text[i]) + key;
//边界归0如果游标超过了
if (index >= table.Length) index -= table.Length;
cipherText += table[index]; //text是字符串用加等
}
return cipherText;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="table">密码本</param>
/// <param name="text">暗文</param>
/// <param name="key">偏移量</param>
/// <returns></returns>
static string Decode(string table,string text,int key)
{
string clearText = "";
for (int i = 0; i < text.Length; i++)
{
int index = table.IndexOf(text[i])-key;
if (index < 0) index += table.Length;
clearText += table[index];
}
return clearText;
}
}
}