如何在OFB模式下在C#中使用3DES解密?

时间:2011-02-03 11:54:04

标签: c# encryption 3des

昨晚我发布了同样的问题,但我提供了一个非常糟糕的代码示例。希望这会让我更容易理解我的情况。

我需要解密使用带有空填充的OFB模式中的3DES加密的消息。

这是我尝试使用从网络抓取的代码进行解密。

加密的消息,密钥和IV都被验证为正确。

它会产生以下错误:

发生加密错误:指定密钥不是此算法的有效大小。

假设其他所有代码都很好,我该如何更改密码模式以使其为带有空填充的OFB?

使用System; 使用System.Collections.Generic; 使用System.Text;

命名空间_DESapp {     使用系统;     使用System.Security.Cryptography;     使用System.Text;     使用System.IO;

class TrippleDESCSPSample
{

    static void Main()
    {
        try
        {
            int discarded;
            byte[] encrypteddata = Convert.FromBase64String( "zbv67qbzN6pD2Uaog62u8WgZOcOz");
            byte[] key = Convert.FromBase64String( "wSQ90YI+lAauwVVSySAi8u0P");
            byte[] IV = HexEncoding.GetBytes("ac3834bfbda8eb07", out discarded);

            string decrypteddata = DecryptTextFromMemory( encrypteddata, key, IV);

            Console.ReadLine();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }

    public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).

            ICryptoTransform des = new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV);

            CryptoStream csDecrypt = new CryptoStream(msDecrypt, des, CryptoStreamMode.Read);
            //CryptoStream csDecrypt = new CryptoStream(msDecrypt,
            //    new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
            //    CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it.
            return new ASCIIEncoding().GetString(fromEncrypt);
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }


    public class HexEncoding
    {
        public HexEncoding()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static byte[] GetBytes(string hexString, out int discarded)
        {
            discarded = 0;
            string newString = "";
            char c;
            // remove all none A-F, 0-9, characters
            for (int i = 0; i < hexString.Length; i++)
            {
                c = hexString[i];
                if (IsHexDigit(c))
                    newString += c;
                else
                    discarded++;
            }
            // if odd number of characters, discard last character
            if (newString.Length % 2 != 0)
            {
                discarded++;
                newString = newString.Substring(0, newString.Length - 1);
            }

            int byteLength = newString.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                hex = new String(new Char[] { newString[j], newString[j + 1] });
                bytes[i] = HexToByte(hex);
                j = j + 2;
            }
            return bytes;
        }

        public static bool IsHexDigit(Char c)
        {
            int numChar;
            int numA = Convert.ToInt32('A');
            int num1 = Convert.ToInt32('0');
            c = Char.ToUpper(c);
            numChar = Convert.ToInt32(c);
            if (numChar >= numA && numChar < (numA + 6))
                return true;
            if (numChar >= num1 && numChar < (num1 + 10))
                return true;
            return false;
        }

        private static byte HexToByte(string hex)
        {
            if (hex.Length > 2 || hex.Length <= 0)
                throw new ArgumentException("hex must be 1 or 2 characters in length");
            byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return newByte;
        }

    }

}

}

0 个答案:

没有答案