C#完成簡略單純的加密、解密字符串對象類實例。本站提示廣大學習愛好者:(C#完成簡略單純的加密、解密字符串對象類實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成簡略單純的加密、解密字符串對象類實例正文
本文實例講述了C#完成簡略單純的加密、解密字符串對象類。分享給年夜家供年夜家參考。詳細以下:
這裡的類CypherHelper是一個用於加密、解密字符串的對象類~~~,合適於便利地加密、解密長度較短的暗碼等字符串(C#外面曾經有了庫System.Security.Cryptography,關於比擬長的字符串或流來講是一個更好的選擇)
類CypherHelper代碼:
class CypherHelper { /// <summary> /// 加密字符串 /// </summary> /// <param name="word">被加密字符串</param> /// <param name="key">密鑰</param> /// <returns>加密後字符串</returns> public static string Encrypt(string word, string key) { if (!System.Text.RegularExpressions.Regex.IsMatch(key, "^[a-zA-Z]*$")) { throw new Exception("key 必需由字母構成"); } key = key.ToLower(); //逐一字符加密字符串 char[] s = word.ToCharArray(); for (int i = 0; i < s.Length; i++) { char a = word[i]; char b = key[i % key.Length]; s[i] = EncryptChar(a, b); } return new string(s); } /// <summary> /// 加密單個字符 /// </summary> /// <param name="a">被加密字符</param> /// <param name="b">密鑰</param> /// <returns>加密後字符</returns> private static char EncryptChar(char a, char b) { int c = a + b - 'a'; if (a >= '0' && a <= '9') //字符0-9的轉換 { while (c > '9') c -= 10; } else if (a >= 'a' && a <= 'z') //字符a-z的轉換 { while (c > 'z') c -= 26; } else if (a >= 'A' && a <= 'Z') //字符A-Z的轉換 { while (c > 'Z') c -= 26; } else return a; //不再下面的規模內,不轉換直接前往 return (char)c; //前往轉換後的字符 } /// <summary> /// 解密字符串 /// </summary> /// <param name="word">被解密字符串</param> /// <param name="key">密鑰</param> /// <returns>解密後字符串</returns> public static string Decrypt(string word, string key) { if (!System.Text.RegularExpressions.Regex.IsMatch(key, "^[a-zA-Z]*$")) { throw new Exception("key 必需由字母構成"); } key = key.ToLower(); //逐一字符解密字符串 char[] s = word.ToCharArray(); for (int i = 0; i < s.Length; i++) { char a = word[i]; char b = key[i % key.Length]; s[i] = DecryptChar(a, b); } return new string(s); } /// <summary> /// 解密單個字符 /// </summary> /// <param name="a">被解密字符</param> /// <param name="b">密鑰</param> /// <returns>解密後字符</returns> private static char DecryptChar(char a, char b) { int c = a - b + 'a'; if (a >= '0' && a <= '9') //字符0-9的轉換 { while (c < '0') c += 10; } else if (a >= 'a' && a <= 'z') //字符a-z的轉換 { while (c < 'a') c += 26; } else if (a >= 'A' && a <= 'Z') //字符A-Z的轉換 { while (c < 'A') c += 26; } else return a; //不再下面的規模內,不轉換直接前往 return (char)c; //前往轉換後的字符 } }
Main函數挪用示例
class Program { static void Main(string[] args) { //1.加密 string a = CypherHelper.Encrypt("TsybiusLee1234", "Galatea"); Console.WriteLine("加密:TsybiusLee1234 → " + a); //2.解密 string b = CypherHelper.Decrypt(a, "Galatea"); Console.WriteLine("解密:" + a + " → " + b); Console.ReadLine(); } }
運轉成果
願望本文所述對年夜家的C#法式設計有所贊助。