C#设计模式系列 3 ----Strategy 策略模式 之--007大破密码危机
1.理论定义
策略模式 定义了 多套算法,这些算法在 客户端 可以任意切换。
2.应用举例
需求描述:话说007在皇家赌场赌牌,突然接到M夫人的急电,要求立刻去非洲 寻找一个DES对称算法密钥,以破解敌人的军*情*机*密
1、(英*国*军*情*六*局)MI6=Military Intelligence 6 截获了 一个非*洲战*区军*事*机*密文件,采用 MD5,RAS,加密,解密,都无法破解
后来发现,这文件被DES加密, 必须找回对称密钥,才可以破解
2、邦德 火速赶往 非洲,目标只有一个:找到密钥。
3.具体编码
1.定义安全 算法接口,里面有加密和解密方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Com.Design.Gof.Strategy { public interface ISecurity { /// <summary> /// 加密 /// </summary> /// <param name="EncryptString">要加密字符串</param> /// <returns></returns> string Encrypt(string EncryptString); /// <summary> /// 解密 /// </summary> /// <param name="EncryptString">要解密字符串</param> /// <returns></returns> string Decrypt(string EncryptString); } }
2.MD5加密
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; namespace Com.Design.Gof.Strategy { public class MD5 : ISecurity { /// <summary> /// 用MD5加密 /// </summary> /// <param name="s"></param> /// <returns></returns> public string Encrypt(string s) { byte[] b = Encoding.Default.GetBytes(s); b = new MD5CryptoServiceProvider().ComputeHash(b); string output = ""; for (int i = 0; i < b.Length; i++) output += b[i].ToString("x").PadLeft(2, '0'); return output; } /// <summary> /// MD5不提供解密 /// </summary> /// <param name="EncryptString"></param> /// <returns></returns> public virtual string Decrypt(string EncryptString) { return string.Empty; } } }
3.RSA加密
using System; using System.Text; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Com.Design.Gof.Strategy { public class RSA:ISecurity { private static readonly string key=new RSACryptoServiceProvider().ToXmlString(true); /// <summary> /// RSA加密函数 /// </summary> /// <param name="xmlPublicKey">说明:KEY必须是XML的行式,返回的是字符串</param> /// <param name="EncryptString"></param> /// <returns></returns> public string Encrypt(string s) { try { byte[] PlainTextBArray; byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(key); PlainTextBArray = (new UnicodeEncoding()).GetBytes(s); CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } catch { return "敌人密码太难破解,已经超过了RSA算法的承受能力,要采取分段加密"; } } /// <summary> /// RSA解密函数 /// </summary> /// <param name="xmlPrivateKey"></param> /// <param name="DecryptString"></param> /// <returns></returns> public string Decrypt(string s) { try { byte[] PlainTextBArray; byte[] DypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(key); PlainTextBArray = Convert.FromBase64String(s); DypherTextBArray = rsa.Decrypt(PlainTextBArray, false); Result = (new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } catch { return "敌人密码太难破解,已经超过了RSA算法的承受能力,要采取分段解密"; } } } }
4.DES加密
using System; using System.Text; using System.IO; using System.Security.Cryptography; /// <summary> ///MethodResult 的摘要说明 /// </summary> namespace Com.Design.Gof.Strategy { public class DES:ISecurity { private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; //密钥向量 //加密解密key public string SymmetricKey { get; set; } /// <summary> /// 加密 /// </summary> /// <param name="EncryptString">待加密的字符串</param> /// <param name="EncryptKey">加密密钥</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public string Encrypt(string EncryptString) { byte[] byKey = null; byKey = System.Text.Encoding.UTF8.GetBytes(SymmetricKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(EncryptString); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } /// <summary> /// 解密 /// </summary> /// <param name="EncryptString">待解密的字符串</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public string Decrypt(string EncryptString) { byte[] byKey = null; byte[] inputByteArray = new Byte[EncryptString.Length]; try { byKey = System.Text.Encoding.UTF8.GetBytes(SymmetricKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(EncryptString); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = new System.Text.UTF8Encoding(); return encoding.GetString(ms.ToArray()); } catch { return ""; } } } }
5 (英*国*军*情*六*局)MI6=Military Intelligence 6
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Com.Design.Gof.Strategy { /// <summary> /// (英*国*军*情*六*局)MI6=Military Intelligence 6 /// </summary> public class MilitaryIntelligence6 {/// <summary> /// 安全策略 /// </summary> private ISecurity Security { get; set; } /// <summary> /// 被加密的军*情*信*息 /// </summary> public string ClassifiedInfomation { get; set; } /// <summary> /// 加密 /// </summary> /// <param name="s"></param> /// <returns></returns> public string Encrypt() { return Security.Encrypt(ClassifiedInfomation); } /// <summary> /// 解密 /// </summary> /// <param name="s"></param> /// <returns></returns> public string Decrypt(string s) { return Security.Decrypt(s); } } }
6.主函数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Com.Design.Gof.Strategy; namespace Com.Design.Gof.Test { class Program { /// <summary> /// 往期 设计模式测试项目是一起的,想测试谁,就调用谁 /// </summary> /// <param name="args"></param> static void Main(string[] args) { MilitaryIntelligence6 MI6= new MilitaryIntelligence6 { //默认密码策略 MD5 Security = new MD5(), //被加密的 军*情*信*息 ClassifiedInfomation = @"+30/SxY2HZ0UtqUVNGMsad0zfajsHQmja1NVC+639zC6y0dE/8XDZJefMl0NwBJ+sUA8LC8k/IPEeTtFqW6OWaaZH9A+TNWzrJ6MSV2qiM3px6wFAyDkJsMKex0mJNe5", }; //用 MD5 破解 string result_md5 = MI6.Encrypt(); Console.WriteLine("用MD5破解敌*人机密文件:" + result_md5); Console.WriteLine("MD5加密后,还是一团乱麻,机密文件无法破解"); Console.WriteLine(); //用 RSA 破解 MI6.Security = new RSA(); string Result_RSA = MI6.Encrypt(); Console.WriteLine(Result_RSA); //用 DES 破解 string symmetricKey = "AfricaArea";//007完成使命,拿到了密钥 MI6.Security = new DES { SymmetricKey = symmetricKey }; //解密后的内容应该是:军-情-机-密-信-息:我军将要攻打 非*洲,战区指挥官:隆美尔,坦克:500辆,飞机:2000架 Console.WriteLine(); Console.WriteLine("007获取到了DES解密密码,打开了 军-事-机-密文件,内容如下:" + MI6.Decrypt(MI6.ClassifiedInfomation)); Console.ReadKey(); } } }
7.运行结果
8.总结
RSA算法还值得进一步去看下,字符过长时候,如何进行分段加密。
借鉴了 孤狼晖 的意见,去除了 枚举和 Switch,直接在客户端New 算法。
附件里面包括了程序源码。
这里是附件下载(Download)