.NET中DES的弱密钥

时间:2014-02-14 08:33:38

标签: c# .net reflection cryptography des

我需要使用零键执行DES加密和解密操作。我在social.msdn.microsoft.com上找到了这个代码,它绕过了对DES密钥的检查.net强加:

public static class DESCryptoExtensions {
    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv) {
        // reflective way of doing what CreateEncryptor() does, bypassing the check for weak keys
        MethodInfo mi = cryptoProvider.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance);
        object[] Par = { key, cryptoProvider.Mode, iv, cryptoProvider.FeedbackSize, 0 };
        ICryptoTransform trans = mi.Invoke(cryptoProvider, Par) as ICryptoTransform;
        return trans;
    }

    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider) {
        return CreateWeakEncryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }

    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv) {
        return CreateWeakEncryptor(cryptoProvider, key, iv);
    }

    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider) {
        return CreateWeakDecryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }
}

我正在使用这个类来封装加密和解密:

public class SimpleDES {
    private readonly byte[] IV = new byte[8] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    private byte[] mKey;
    private DESCryptoServiceProvider des;

    public SimpleDES(byte[] aKey) {
        if (aKey.Length != 8)
            throw new Exception("Key size must be 8 bytes");
        mKey = aKey;
        des = new DESCryptoServiceProvider();
        des.BlockSize = 64;
        des.KeySize = 64;
        des.Padding = PaddingMode.None;
    }

    public byte[] Encrypt(byte[] data) {
        if (data.Length != 8)
            throw new Exception("Data size must be 8 bytes");

        ICryptoTransform encryptor = des.CreateWeakEncryptor(mKey, IV);
        return encryptor.TransformFinalBlock(data, 0, data.Length);
    }

    public byte[] Decrypt(byte[] data) {
        if (data.Length != 8)
            throw new Exception("Data size must be 8 bytes");
        ICryptoTransform decryptor = des.CreateWeakDecryptor(mKey, IV);
        return decryptor.TransformFinalBlock(data, 0, data.Length);
    }
}

虽然Encrypt()完美无缺,但Decrypt()的返回值与Encrypt()相同。我是C#的新手,我迷路了。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

这很简单。您在CreateDecryptor方法中调用相同的方法CreateWeakEncryptor。所以,最后    MethodInfo mi = cryptoProvider.GetType()。GetMethod(“_ NewEncryptor”,BindingFlags.NonPublic | BindingFlags.Instance);

始终返回加密方法。在调用时,该方法将0作为最后一个参数传递,该参数始终等于枚举CryptoAPITransformMode.Encrypt。

相反,你必须在解密时传递1个CryptoAPITransformMode.Decrypt。