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

时间:2021-11-27 08:29:32

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

一、理论定义

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

二、应用举例

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

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

三、具体编码

1.定义安全 算法接口,里面有加密和解密方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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加密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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加密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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加密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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.主函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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.运行结果

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

8.总结

rsa算法还值得进一步去看下,字符过长时候,如何进行分段加密。

借鉴了 孤狼晖 的意见,去除了 枚举和 switch,直接在客户端new 算法。

附:完整实例代码点击此处本站下载

希望本文所述对大家c#程序设计有所帮助。

原文链接:http://www.cnblogs.com/HCCZX/archive/2012/08/01/2618078.html