2.1 原理介绍
凯撒密码是一种很古老的加密体制,主要是通过代换来达到加密的目的。其基本思想是:通过把字母移动一定的位数来实现加密和解密。移动位数就是加密和解密的密钥。
举例说明,假设明文为“ABCD”,密钥设置为7,那么对应的密文就是“HIJK”。具体流程如下表所示:.

2.2 C#代码
// Caesar Cipher(凯撒密码)
public sealed class Caesar
{
    // 加密
    public static string CaesarEncrypt(string plaintext, int key)
    {
        // 字符串转换为字节数组
        byte[] origin = Encoding.ASCII.GetBytes(plaintext);
        string rst = null;
 
        for (int i = 0; i < origin.Length; i++)
        {
            // 获取字符ASCII码
            int asciiCode = (int)origin[i];
 
            // 偏移
            asciiCode += key;
            byte[] byteArray = new byte[] { (byte)asciiCode };
 
            // 将偏移后的数据转为字符
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(byteArray);
 
            // 拼接数据
            rst += strCharacter;
        }
        return rst;
    }
 
    // 解密
    public static string CaesarDecrypt(string ciphertext, int key)
    {
        // 字符串转换为字节数组
        byte[] origin = Encoding.ASCII.GetBytes(ciphertext);
        string rst = null;
 
        for (int i = 0; i < origin.Length; i++)
        {
            // 获取字符ASCII码
            int asciiCode = (int)origin[i];
 
            // 偏移
            asciiCode -= key;
            byte[] byteArray = new byte[] { (byte)asciiCode };
 
            // 将偏移后的数据转为字符
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(byteArray);
 
            // 拼接数据
            rst += strCharacter;
        }
        return rst;
    }
}