We simply have two methods, one that encrypts the data, and one that decrypts it.
You can see that each method can revert the changes made by the other.
public static Byte[] Encrypt(Byte[] data, Byte[] pass) { Int32 dLen = data.Length, pLen = pass.Length, pSum = pLen, n = 0; for (Int32 i = 0; i < pLen; i++) pSum += pass[i]; for (Int32 i = 0; i < dLen; i++) { data[i] += (Byte)(pass[n++] + pSum); if (n == pLen) { n = 0; pSum += pLen; } } return data; }
public static Byte[] Decrypt(Byte[] data, Byte[] pass) { Int32 dLen = data.Length, pLen = pass.Length, pSum = pLen, n = 0; for (Int32 i = 0; i < pLen; i++) pSum += pass[i]; for (Int32 i = 0; i < dLen; i++) { data[i] -= (Byte)(pass[n++] + pSum); if (n == pLen) { n = 0; pSum += pLen; } } return data; }Both methods receive Byte array parameters, so you'll have to convert the strings to use any.
The last two methods can encrypt a String and return the resulting bytes, that you can write to a file for example, and can decrypt the encrypted bytes and return the original String value.
public static Byte[] EncryptString(String text, String pass) { Byte[] textData = Encoding.Unicode.GetBytes(text); Byte[] passData = Encoding.Unicode.GetBytes(pass); return Encrypt(textData, passData); }
public static String DecryptBytes(Byte[] textData, String pass) { Byte[] passData = Encoding.Unicode.GetBytes(pass); return Encoding.Unicode.GetString(Decrypt(textData, passData)); }Mind not to try to decrypt the encrypted text that you placed in a textbox or such.
Some encrypted characters are not displayed by the textbox and therefore will be lost,
and the Text property of the textbox will not retrieve the complete data.
These methods can of course be used to encrypt/decrypt any array of bytes.
The full code is below. Let me know if you run into any difficulties with it.
using System; using System.Text; namespace CodeSlurm { public sealed class Data { public static Byte[] Encrypt(Byte[] data, Byte[] pass) { Int32 dLen = data.Length, pLen = pass.Length, pSum = pLen, n = 0; for (Int32 i = 0; i < pLen; i++) pSum += pass[i]; for (Int32 i = 0; i < dLen; i++) { data[i] += (Byte)(pass[n++] + pSum); if (n == pLen) { n = 0; pSum += pLen; } } return data; } public static Byte[] Decrypt(Byte[] data, Byte[] pass) { Int32 dLen = data.Length, pLen = pass.Length, pSum = pLen, n = 0; for (Int32 i = 0; i < pLen; i++) pSum += pass[i]; for (Int32 i = 0; i < dLen; i++) { data[i] -= (Byte)(pass[n++] + pSum); if (n == pLen) { n = 0; pSum += pLen; } } return data; } // public static Byte[] EncryptString(String text, String pass) { Byte[] textData = Encoding.Unicode.GetBytes(text); Byte[] passData = Encoding.Unicode.GetBytes(pass); return Encrypt(textData, passData); } public static String DecryptBytes(Byte[] textData, String pass) { Byte[] passData = Encoding.Unicode.GetBytes(pass); return Encoding.Unicode.GetString(Decrypt(textData, passData)); } } }