tags:

views:

47

answers:

1
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;
        }
    }

}
A: 

The same key (Key) and initialization vector (IV) used to encrypt the file must be used to decrypt it. I can't fully check this code currently so there may be one or two small problems but give it a try and let me know if it works, hopefully you get the idea:

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;
    }
}
Peter McGrattan
Still I am getting this error..
Jitendra Jadav
see problem is like this encrypt and decrypt bytes would not match ..
Jitendra Jadav
Are you sure you're using exactly the same key (Key) and initialization vector (IV)? There is a full example for how to encrypt and decrypt using a MemoryStream on msdn here, scroll down to the middle of this webpage: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx
Peter McGrattan
Sure Exactly we are following this example..but when you Encrypt and decrypt at the same time suppose this console application, this is working properly.but we r using first registration time Encrypt Data and when we adduser at that time we call decrypt method so it would be quit defferent bytes of data and key as well IV so this is the main problem..tell me what to do..thanks.
Jitendra Jadav
Of course the data bytes[] will be different but the (Key) and (IV) MUST be the same as that used to encrypt. So always use the same (Key) and (IV) when you encrypt and decrypt, store them in a static class that is available everywhere in your app, I can't be any clearer than that.
Peter McGrattan
I'll give my whole class ecrypt and decrypt u see where i made my mistak and suggest me..thanks...
Jitendra Jadav