• 3DES加密及.NET弱密钥处理


    背景

           智能pos机开发项目需要指定Key加密某些关键字符串。商定采用3DES加密算法。

    实践

           网海中很多.NET C#编写3DES加密的函数。采集一段简明、成熟的代码,归置于常用程序集。但当指定Key为8位(位数比较短)时,抛出了异常。原来.NET会自动检测Key的长度,认为8位是弱秘钥。

    于是发现能手重写的方法,奏效:

    private static byte[] ThreeDES(byte[] key, byte[] str)
    {
           TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();
           tdsc.Padding = PaddingMode.None;

           byte[] IV = { 0xB0, 0xA2, 0xB8, 0xA3, 0xDA, 0xCC, 0xDA, 0xCC };
           //指定密匙长度,默认为192位
           tdsc.KeySize = 128;
           //使用指定的key和IV(加密向量)
           Type t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode");
           object obj = t.GetField("Encrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t);
           MethodInfo mi = tdsc.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic);
           ICryptoTransform desCrypt = (ICryptoTransform)mi.Invoke(tdsc, new object[] { key, CipherMode.ECB, null, 0, obj });
           tdsc.IV = IV;
           //加密模式,偏移
           tdsc.Mode = CipherMode.ECB;

           //进行加密转换运算
           //ICryptoTransform ct = tdsc.CreateDecryptor();
           //8很关键,加密结果是8字节数组
           byte[] results = desCrypt.TransformFinalBlock(str, 0, 8);

           return results;
    }

  • 相关阅读:
    PHP入门03 -- 数组与数据结构
    PHP入门02 -- 函数
    PHP入门01 -- 基本语法
    node文章
    Mongodb08
    Mongodb07
    ISO处理jq事件
    map
    Django自定义模板
    JS this指向
  • 原文地址:https://www.cnblogs.com/johsan/p/7889110.html
Copyright © 2020-2023  润新知