解密密钥值不匹配

时间:2010-05-06 09:09:36

标签: c# encryption

public class TrippleENCRSPDESCSP
{


    public TrippleENCRSPDESCSP()
    {

    }

    public void EncryptIt(string sData,ref byte[] sEncData,ref byte[] Key1,ref byte[] Key2)
    {
        try
        {
            // Create a new TripleDESCryptoServiceProvider object
            // to generate a key and initialization vector (IV).
            TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();

            // Create a string to encrypt.

            // Encrypt the string to an in-memory buffer.
            byte[] Data = EncryptTextToMemory(sData,tDESalg.Key,tDESalg.IV);
            sEncData = Data;
            Key1 = tDESalg.Key;
            Key2 = tDESalg.IV;


        }
        catch (Exception)
        {

            throw;
        }


    }

    public string DecryptIt(byte[] sEncData)
    {

        //byte[] toEncrypt = new ASCIIEncoding().GetBytes(sEncData);

        //XElement xParser = null;
        //XmlDocument xDoc = new XmlDocument();

        try
        {
            //string Final = "";
            string sPwd = null;
            string sKey1 = null;
            string sKey2 = null;
            //System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            string soutxml = "";

            //soutxml = encoding.GetString(sEncData);
            soutxml = ASCIIEncoding.ASCII.GetString(sEncData);
            sPwd = soutxml.Substring(18, soutxml.LastIndexOf("</EncPwd>") - 18);
            sKey1 = soutxml.Substring(18 + sPwd.Length + 15, soutxml.LastIndexOf("</Key1>") - (18 + sPwd.Length + 15));
            sKey2 = soutxml.Substring(18 + sPwd.Length + 15 + sKey1.Length + 13, soutxml.LastIndexOf("</Key2>") - (18 + sPwd.Length + 15 + sKey1.Length + 13));



            //xDoc.LoadXml(soutxml);

           //xParser = XElement.Parse(soutxml);

        //IEnumerable<XElement> elemsValidations =
        //      from el in xParser.Elements("EmailPwd")
        //     select el;


            #region OldCode
            //XmlNodeList objXmlNode = xDoc.SelectNodes("EmailPwd");

            //foreach (XmlNode xmllist in objXmlNode)
            //{
            //    XmlNode xmlsubnode;
            //    xmlsubnode = xmllist.SelectSingleNode("EncPwd");
            //    xmlsubnode = xmllist.SelectSingleNode("Key1");
            //    xmlsubnode = xmllist.SelectSingleNode("Key2");
            //}

            #endregion

        //foreach (XElement elemValidation in elemsValidations)
        //{
        //    sPwd = elemValidation.Element("EncPwd").Value;
        //    sKey1 = elemValidation.Element("Key1").Value;
        //    sKey2 = elemValidation.Element("Key2").Value;
        //}

            //byte[] Key1 = encoding.GetBytes(sKey1);
            //byte[] Key2 = encoding.GetBytes(sKey2);
            //byte[] Data = encoding.GetBytes(sPwd);


            byte[] Key1 = ASCIIEncoding.ASCII.GetBytes(sKey1);
            byte[] Key2 = ASCIIEncoding.ASCII.GetBytes(sKey2);
            byte[] Data = ASCIIEncoding.ASCII.GetBytes(sPwd);

            // Decrypt the buffer back to a string.
            string Final = DecryptTextFromMemory(Data, Key1, Key2);

            return Final;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public static byte[] EncryptTextToMemory(string Data,byte[] Key,byte[] IV)
    {
        try
        {
            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(mStream,
                new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);

            // Convert the passed string to a byte array.
            //byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
            byte[] toEncrypt = ASCIIEncoding.ASCII.GetBytes(Data);
            // Write the byte array to the crypto stream and flush it.
            cStream.Write(toEncrypt, 0, toEncrypt.Length);
            cStream.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = mStream.ToArray();

            // Close the streams.
            cStream.Close();
            mStream.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException e)
        {
            MessageBox.Show("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }

    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). 
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
            new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
            CryptoStreamMode.Write);

            csDecrypt.Write(Data, 0, Data.Length);
            //csDecrypt.FlushFinalBlock();
            msDecrypt.Position = 0;

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

            // Read the decrypted data out of the crypto stream 
            // and place it into the temporary buffer. 
            msDecrypt.Read(fromEncrypt, 0, msDecrypt.ToArray().Length);
            //csDecrypt.Close();
            MessageBox.Show(ASCIIEncoding.ASCII.GetString(fromEncrypt));
            //Convert the buffer into a string and return it. 
            return new ASCIIEncoding().GetString(fromEncrypt);

        }
        catch (CryptographicException e)
        {
            MessageBox.Show("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }

}

1 个答案:

答案 0 :(得分:0)

必须使用用于加密文件的相同密钥(密钥)和初始化向量(IV)来解密它。我目前无法完全检查此代码,因此可能存在一两个小问题,但请尝试一下,如果有效,请告诉我,希望您能得到这个想法:

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();

        // Create a CryptoStream using the MemoryStream
        // and the passed key and initialization vector (IV).
        CryptoStream csDecrypt = new CryptoStream(msDecrypt,
        new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
        CryptoStreamMode.Write);

        csDecrypt.Write(Data, 0, Data.Length);
        csDecrypt.FlushFinalBlock();
        msDecrypt.Position = 0;

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

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

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