凯撒密码 理解

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;
        }


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值