TQC+ C# 認證教學手冊

206、加解密

本題使用 .NET Framework 內建的 SymmetricAlgorithm 進行加解密。

應具備能力:

  1. 查閱 MSDN API 文件。
  2. 瞭解正確使用 Method 參數。

SymmetricAlgorithm

參考 MSDN 文件

SymmetricAlgorithm.CreateEncryptor Method

https://msdn.microsoft.com/en-us/library/09d0kyb3(v=vs.90).aspx

參考程式碼

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace CSD02
{
    class Program
    {
        static void Main(string[] args)
        {
            //接收使用者輸入字串
            Console.WriteLine("輸入加密字串:");
            string word = Console.ReadLine();

            //使用DESCryptoServiceProvider 類別加密
            byte[] secret = Encrypt(word, new DESCryptoServiceProvider());
            Console.WriteLine("加密後字串:" + new UTF8Encoding().GetString(secret));
            //Console.WriteLine("加密後字串:" + Convert.ToBase64String(secret));

            //使用DESCryptoServiceProvider 類別解密
            string untie = Decrypt(secret, new DESCryptoServiceProvider());
            Console.WriteLine("解密後字串:" + untie);

            Console.ReadLine();
        }

        //加解密的金鑰
        static string encryptKey = "TQC+";

        //加密函式
        static byte[] Encrypt(string PlainText, SymmetricAlgorithm Algorithm)
        {

            MemoryStream ms = new MemoryStream();
            byte[] key = Encoding.Unicode.GetBytes(encryptKey);

            CryptoStream encStream = new CryptoStream(ms, Algorithm.CreateEncryptor(key, key), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(encStream);
            sw.WriteLine(PlainText);

            byte[] buffer = null;

            buffer = ms.ToArray();

            sw.Close();
            encStream.Close();
            ms.Close();

            return buffer;
        }

        //解密函式
        static string Decrypt(byte[] CypherText, SymmetricAlgorithm Algorithm)
        {
            MemoryStream ms = new MemoryStream(CypherText);

            byte[] key = Encoding.Unicode.GetBytes(encryptKey);

            CryptoStream encStream = new CryptoStream(ms, Algorithm.CreateDecryptor(key, key), CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(encStream);
            string val = "";

            val = sr.ReadToEnd();

            sr.Close();
            encStream.Close();
            ms.Close();

            return val;
        }
    }
}