3

I got a textbox and a 'decrypt' button in my Windows Form Application where I put an encrypted string in there and try to decrypt it but the problem is this. First, I got this class code called DataEncryptor from a guy on this website:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

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

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

And he gave the usage of it:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);

I copied his code and works at encrypting and decrypting:

//my code
private void proceedED(string data)
{
    DataEncryptor key = new DataEncryptor();
    string encr = key.EncryptString(data);
    string actual = key.DecryptString(encr);
    encryptedLabel.Text = encr;
    decryptedLabel.Text = actual;     
}

Then I created a method like this:

private void proceedDecrypt(string data) 
{
    DataEncryptor key = new DataEncryptor();
    string decr = key.DecryptString(data);
    decryptedData.Text = decr;
}

The problem is that it crashes when I submit and I don't know why. I think it should be a true encrypted string because it's just a normal string. How do I fix this?

newbieguy
  • 658
  • 2
  • 11
  • 29
  • What exception is it giving? In all posts about "errors", "crahes" etc. include the message and stacktrace of an exception? Maybe, you haven't initialized a key or something's wrong with your `data`. We can't know it without an exception message. – Yeldar Kurmangaliyev Jun 12 '15 at 04:36
  • `Array cannot be null Paramater name: bytes` the line error is in the DecryptString(string data) method at the bottom of the DataEncryptor class – newbieguy Jun 12 '15 at 04:38
  • 1
    It looks like you created method `proceedDecrypt` but pass empty `data` to it. Looks at the place you call this method. – Yeldar Kurmangaliyev Jun 12 '15 at 04:39
  • i think it needs to be a true encrypted string because its just a normal string – newbieguy Jun 12 '15 at 04:48
  • Hmm, this code looks quite familiar to me. See http://stackoverflow.com/a/10176980/380384 – John Alexiou Jun 12 '15 at 04:50
  • Related post: http://security.stackexchange.com/questions/12071/how-to-store-iv-and-key-temporarily-but-securely – John Alexiou Jun 12 '15 at 05:20

4 Answers4

1

Each instance of DataEncryptor generates new keys. You need to use the same keys which encrypted the string to decrypt. If this is done in the same process then keep a reference to DataEncryptor key. Otherwise you need to initialize using the DataEncryptor(byte[] key, byte[] iv) constructor.

Try code like this:

class Program
{
    static void Main(string[] args)
    {
        string key, iv;

        var plain="A very secret message.";
        var cipher=EncryptString(plain, out key, out iv);

        // Later ...

        var message=DecryptString(cipher, key, iv);
    }

    public static string EncryptString(string plain, out string key, out string iv)
    {
        var crypto=new DataEncryptor();
        iv=Convert.ToBase64String(crypto.IV);
        key=Convert.ToBase64String(crypto.Key);
        return crypto.EncryptString(plain);
    }

    public static string DecryptString(string cipher, string key, string iv)
    {
        var crypto=new DataEncryptor(
            Convert.FromBase64String(key), 
            Convert.FromBase64String(iv));

        return crypto.DecryptString(cipher);
    }
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
0

you are creating new object in both function;

DataEncryptor key = new DataEncryptor();

That is the reason, for your error.

Just declare;

   DataEncryptor key = new DataEncryptor();

Out side of your proceedED() and proceedDecrypt(), I mean make it public.

OR you can pass pass key as parameter to proceedDecrypt() and use it in that function.

Like;

DataEncryptor key = new DataEncryptor();

private void proceedED(string data)
{
  string encr = key.EncryptString(data);
  string actual = key.DecryptString(encr);
  encryptedLabel.Text = encr;
  decryptedLabel.Text = actual; 
  proceedDecrypt(encr);    
}

private void proceedDecrypt(string data) 
{

    string decr = key.DecryptString(data);
    decryptedData.Text = decr;
}

Hope it helps..!!!

H. Mahida
  • 2,356
  • 1
  • 12
  • 23
  • check the edit, and if error then tell me what error you get....!!! Also how you are calling proceedDecrypt() function ? – H. Mahida Jun 12 '15 at 05:04
0

You can use encryption and decription with System.Security.Cryptography

1) Set encryption decription key
2) Encrypt data with encryption key
3) Decrypt data with same encryption key

Please refer below link with Encryption and Decription example. Encryption/Decryption Function in .NET using the TripleDESCryptoServiceProvider Class

Rohit Sonaje
  • 522
  • 4
  • 14
0

Well I finally solved it...

I copied this code from https://social.msdn.microsoft.com/Forums/vstudio/en-US/d6a2836a-d587-4068-8630-94f4fb2a2aeb/encrypt-and-decrypt-a-string-in-c?forum=csharpgeneral

    static readonly string PasswordHash = "P@@Sw0rd";
    static readonly string SaltKey = "S@LT&KEY";
    static readonly string VIKey = "@1B2c3D4e5F6g7H8";

    public static string Encrypt(string plainText)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

        byte[] cipherTextBytes;

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memoryStream.ToArray();
                cryptoStream.Close();
            }
            memoryStream.Close();
        }
        return Convert.ToBase64String(cipherTextBytes);
    }
    public static string Decrypt(string encryptedText)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }

and removed the DataEncryptor class

newbieguy
  • 658
  • 2
  • 11
  • 29