博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#设计模式系列 3 ----Strategy 策略模式 之--007大破密码危机
阅读量:4659 次
发布时间:2019-06-09

本文共 7735 字,大约阅读时间需要 25 分钟。

 

   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    {        ///         /// 加密        ///         /// 要加密字符串        /// 
string Encrypt(string EncryptString); /// /// 解密 /// /// 要解密字符串 ///
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    {        ///         /// 用MD5加密        ///         ///         /// 
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; } /// /// MD5不提供解密 /// /// ///
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);              ///         /// RSA加密函数        ///         /// 说明:KEY必须是XML的行式,返回的是字符串        ///         /// 
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算法的承受能力,要采取分段加密"; } } /// /// RSA解密函数 /// /// /// ///
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; /// ///MethodResult 的摘要说明/// 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; }        ///         /// 加密        ///         /// 待加密的字符串        /// 加密密钥        /// 
加密成功返回加密后的字符串,失败返回源串
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()); } /// /// 解密 /// /// 待解密的字符串 ///
解密成功返回解密后的字符串,失败返源串
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{    ///     /// (英*国*军*情*六*局)MI6=Military Intelligence 6    ///     public class MilitaryIntelligence6    {
/// /// 安全策略 /// private ISecurity Security { get; set; } /// /// 被加密的军*情*信*息 /// public string ClassifiedInfomation { get; set; } /// /// 加密 /// /// ///
public string Encrypt() { return Security.Encrypt(ClassifiedInfomation); } /// /// 解密 /// /// ///
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    {        ///         /// 往期 设计模式测试项目是一起的,想测试谁,就调用谁        ///         ///         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 算法。

  附件里面包括了程序源码。

  这里是附件

转载于:https://www.cnblogs.com/HCCZX/archive/2012/08/01/2618078.html

你可能感兴趣的文章
oracle, group by, having, where
查看>>
nodejs pm2使用
查看>>
CSS选择器总结
查看>>
mysql中sql语句
查看>>
sql语句的各种模糊查询语句
查看>>
C#操作OFFICE一(EXCEL)
查看>>
【js操作url参数】获取指定url参数值、取指定url参数并转为json对象
查看>>
移动端单屏解决方案
查看>>
web渗透测试基本步骤
查看>>
使用Struts2标签遍历集合
查看>>
angular.isUndefined()
查看>>
第一次软件工程作业(改进版)
查看>>
网络流24题-飞行员配对方案问题
查看>>
引入css的四种方式
查看>>
iOS开发UI篇—transframe属性(形变)
查看>>
3月7日 ArrayList集合
查看>>
jsp 环境配置记录
查看>>
Python03
查看>>
LOJ 2537 「PKUWC2018」Minimax
查看>>
使用java中replaceAll方法替换字符串中的反斜杠
查看>>