首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

最簡單的 C# 字串加密:移位密碼實作與安全性分析

     編輯:關於C語言

前言:教學用途的經典移位密碼

凱撒密碼是最古老的替換加密演算法。本文實作一個變體:**加密後字串首字元 = 原字串尾字元,其餘各字元 = 原字串前一字元的 ASCII/Unicode 值 + 3**。雖極不安全,但適合理解字元編碼操作、字串陣列操作、模運算等基礎概念。

演算法規則

輸入:  w e l c o m e  (索引 0~6)
輸出:  e z h o f r p
        ↑ ↑ ↑ ↑ ↑ ↑ ↑
        原[6] 原[0]+3 原[1]+3 原[2]+3 原[3]+3 原[4]+3 原[5]+3

完整 C# 實作

using System;

public class ShiftCipher
{
    /// 
    /// 移位加密:首字元取原尾字元,其餘各字元 = 原前一字元 + 3
    /// 
    public static string Encrypt(string input)
    {
        if (string.IsNullOrEmpty(input)) return input;
        if (input.Length == 1) return new string(new char[] { (char)(input[0] + 3) });

        char[] src = input.ToCharArray();
        char[] dst = new char[src.Length];

        // 首字元 = 原尾字元
        dst[0] = src[src.Length - 1];

        // 其餘字元 = 原前一字元 + 3
        for (int i = 1; i < src.Length; i++)
        {
            int val = src[i - 1] + 3;
            dst[i] = (char)val;
        }

        return new string(dst);
    }

    /// 
    /// 解密:逆向操作
    /// 
    public static string Decrypt(string input)
    {
        if (string.IsNullOrEmpty(input)) return input;
        if (input.Length == 1) return new string(new char[] { (char)(input[0] - 3) });

        char[] src = input.ToCharArray();
        char[] dst = new char[src.Length];

        // 原尾字元 = 加密首字元
        dst[dst.Length - 1] = src[0];

        // 原前一字元 = 加密字元 - 3
        for (int i = 1; i < src.Length; i++)
        {
            int val = src[i] - 3;
            dst[i - 1] = (char)val;
        }

        return new string(dst);
    }

    public static void Main()
    {
        Console.Write("請輸入要加密的字串:");
        string input = Console.ReadLine();

        string encrypted = Encrypt(input);
        string decrypted = Decrypt(encrypted);

        Console.WriteLine($"原文:  {input}");
        Console.WriteLine($"密文:  {encrypted}");
        Console.WriteLine($"解密:  {decrypted}");
        Console.WriteLine($"驗證:  {(input == decrypted ? "通過" : "失敗")}");
    }
}

執行範例

請輸入要加密的字串:welcome
原文:  welcome
密文:  ezhofrp
解密:  welcome
驗證:  通過

程式碼細節解析

  • ToCharArray():字串轉可變字元陣列
  • (char)(val):整數轉字元(隱式截斷超出範圍值)
  • new string(char[]):陣列建構字串
  • 邊界處理:空字串、單字元情況

安全性分析:為何不可用於生產

弱點說明
金鑰空間極小固定位移 3,無金鑰參數,破解成本 O(1)
頻率分析單表替換密碼,字母頻率分布不變,極易破解
已知明文攻擊一組明密文對即可推導完整映射規則
無完整性保護任意修改密文解密後僅局部亂碼,無法偵測竄改
字元溢位未處理char + 3 超過 char.MaxValue 會環繞,解密失敗

改進版:支援任意位移與模運算

public static string EncryptImproved(string input, int shift)
{
    if (string.IsNullOrEmpty(input)) return input;
    shift = shift % 65536; // char 範圍 0~65535
    char[] src = input.ToCharArray();
    char[] dst = new char[src.Length];
    dst[0] = src[^1];
    for (int i = 1; i < src.Length; i++)
        dst[i] = (char)((src[i - 1] + shift) % 65536);
    return new string(dst);
}

public static string DecryptImproved(string input, int shift)
{
    if (string.IsNullOrEmpty(input)) return input;
    shift = shift % 65536;
    char[] src = input.ToCharArray();
    char[] dst = new char[src.Length];
    dst[^1] = src[0];
    for (int i = 1; i < src.Length; i++)
        dst[i - 1] = (char)((src[i] - shift + 65536) % 65536);
    return new string(dst);
}

現代替代:生產級加密建議

  • 對稱加密:Aes.GenerateKey() + Aes.CreateEncryptor()(GCM 模式提供認證加密)
  • 非對稱加密:RSA / ECDsa 簽名與金鑰交換
  • 密碼衍生:Rfc2898DeriveBytes (PBKDF2) / Argon2 將密碼轉金鑰
  • 高層庫:Microsoft.AspNetCore.DataProtection、libsodium-net、NaCl

總結

移位密碼是理解「字元編碼位移」、「字串陣列索引操作」、「可逆演算法設計」的優秀教學範例。**切記:任何自行設計的加密演算法在生產環境皆為零安全性**,請務必使用經過密碼學專家審計、標準化的加密庫與演算法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved