错误数据:在DES解密期间未处理CryptographicException

时间:2014-02-05 12:58:38

标签: c# wpf exception encryption des

使用下面的Encrypt方法,我成功地加密了xml文件,但是当我检查DESDecrypt方法时,为了解密那些xml文件,它会抛出错误

const string DESKey = "AQWSEDRF";
const string DESIV = "HGFEDCBA";


public static string DESDecrypt(string stringToDecrypt)//Decrypt the content
{

    byte[] key;
    byte[] IV;

    byte[] inputByteArray;
    try
    {

        key = Convert2ByteArray(DESKey);

        IV = Convert2ByteArray(DESIV);

        stringToDecrypt = stringToDecrypt.Replace(" ", "+");

        int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);


        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream();

        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);

        cs.FlushFinalBlock();

        Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());
    }

    catch (System.Exception ex)
    {

        throw ex;
    }

}

public static string DESEncrypt(string stringToEncrypt)// Encrypt the content
{

    byte[] key;
    byte[] IV;

    byte[] inputByteArray;
    try
    {

        key = Convert2ByteArray(DESKey);

        IV = Convert2ByteArray(DESIV);

        inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);

        cs.FlushFinalBlock();

        return Convert.ToBase64String(ms.ToArray());
    }

    catch (System.Exception ex)
    {
        throw ex;
    }

}

static byte[] Convert2ByteArray(string strInput)
{

    int intCounter; char[] arrChar;
    arrChar = strInput.ToCharArray();

    byte[] arrByte = new byte[arrChar.Length];

    for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
        arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);

    return arrByte;
}

抛出异常,“坏数据”。 CryptographicException未处理。如何解决这个错误,任何帮助将不胜感激。

0 个答案:

没有答案