Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array cryptography in C#

I want to create a nice cryptography using bitwise operators. However I fail to do so.

I want it to have bitwise operators using a byte array to encrypt and decrypt my byte array.

public class Cryptographer
{
    private byte[] Keys { get; set; }

    public Cryptographer(string password)
    {
        Keys = Encoding.ASCII.GetBytes(password);
    }

    public void Encrypt(byte[] data)
    {
        for(int i = 0; i < data.Length; i++)
        {
            data[i] = (byte) (data[i] & Keys[i]);
        }
    }

    public void Decrypt(byte[] data)
    {
        for (int i = 0; i < data.Length; i++)
        {
            data[i] = (byte)(Keys[i] & data[i]);
        }
    }
}

I know this is wrong, thats why I need help. I simply want it to use 1 string to encrypt and decrypt all data.

like image 591
Basser Avatar asked Nov 26 '22 23:11

Basser


2 Answers

This is what is sometimes known as 'craptography', because it provides the illusion of security while being functionally useless in protecting anything. Use the framework classes if you want to do cryptography right, because it's extremely difficult to roll your own.

Take a look at this for advice on what you are trying to do (encrypt/decrypt) - http://msdn.microsoft.com/en-us/library/e970bs09.aspx. Really your requirements should determine what classes you decide to use. This has good background: http://msdn.microsoft.com/en-us/library/92f9ye3s.aspx

For simple encrypt/decrypt (if this is what you need) DPAPI may be the simplest way.

like image 76
Steve Townsend Avatar answered Nov 29 '22 12:11

Steve Townsend


You seem to be trying to implement the XOR cipher. XOR is ^ in C#:

public void Crypt(byte[] data)
{
    for(int i = 0; i < data.Length; i++)
    {
        data[i] = (byte) (data[i] ^ Keys[i]);
    }                             ↑
}

Since the Encrypt and Decrypt method do exactly the same, you need only one method.

Note, however, that this is just a toy and not suitable to secure data in real-world scenarios. Have a look at the System.Security.Cryptography Namespace which provides many implementations of proven algorithms. Using these correctly is still hard to get right though.

like image 27
dtb Avatar answered Nov 29 '22 13:11

dtb