一聚教程网:一个值得你收藏的教程网站

热门教程

C#设计模式之Strategy策略模式解决007大破密码危机问题示例

时间:2022-06-25 04:33:15 编辑:袖梨 来源:一聚教程网

本文实例讲述了C#设计模式之Strategy策略模式解决007大破密码危机问题。分享给大家供大家参考,具体如下:

一、理论定义

策略模式 定义了 多套算法,这些算法在 客户端 可以任意切换。

二、应用举例

需求描述:话说007在皇家赌场赌牌,突然接到M夫人的急电,要求立刻去非洲 寻找一个DES对称算法密钥,以破解敌人的军*情*机*密

1、(英*国*军*情*六*局)MI6=Military Intelligence 6  截获了 一个非*洲战*区军*事*机*密文件,采用 MD5,RAS,加密,解密,都无法破解
后来发现,这文件被DES加密, 必须找回对称密钥,才可以破解
2、邦德 火速赶往 非洲,目标只有一个:找到密钥。

三、具体编码

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 算法。

热门栏目