Error message: System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length.'
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv;
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++) {
string sNo = Password.Substring(iLoop-1,1);
byte[] asciiBytes = Encoding.ASCII.GetBytes(sNo);
iValue = BitConverter.ToInt32(asciiBytes, 0); ---->**Error**
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
Please Help
Thank
I try to reach your idea because of so many redundancy codes. By using:
SubString exports each character even Encoding.ASCII.GetBytes can return all byte array from these characters
BitConverter expected of 4-byte binary input as well
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32 and seem this function is no help at all
Declare iLoop = 1 but inside loop does iLoop - 1
sPassConv gets value from iTotal so many times, should put outside the loop
Quick fix from your code:
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv = "";
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++)
{
string sNo = Password.Substring(iLoop - 1, 1);
iValue = Encoding.ASCII.GetBytes(sNo)[0];
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
A little bit refactor
public static string PassConv2(string Password, int iL = 3)
{
int iTotal = 0;
var bytes = Encoding.ASCII.GetBytes(Password);
for (var iLoop = 0; iLoop < bytes.Length; iLoop++)
{
// bytes[iLoop] = iValue
iTotal += bytes[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
This function is need to be improved because it does loop 2 times, first to bytes and second to calculate. Since every character can convert to ASCII even Extended ASCII, so we could cast it directly. PassConv3 gives more exact when input is Unicode such as "Áaa", the Encoding.ASCII.GetByteswill cast as "?aa" with '?' represents 63 ASCII
public static string PassConv3(string Password, int iL = 3)
{
int iTotal = 0;
for (var iLoop = 0; iLoop < Password.Length; iLoop++)
{
iTotal += Password[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
And the result
public static void MainFunc()
{
Console.WriteLine(PassConv("ABCD")); // 1202
Console.WriteLine(PassConv2("ABCD")); // 1202
Console.WriteLine(PassConv3("ABCD")); // 1202
}
Hope it helps !
Related
I'm currently trying to shift a BitArray while keeping its length. Since there's no built-in method I'm struggling to build one but can't make it work, unfortunatly.
My initial BitArray code sets a length of 421 for the BitArray.
var b = new BitArray(length: 421);
Than, I'm assigning some values for testing. For instance:
b.Set(0, true);
b.Set(1, true);
However, I can't figure out how to shift the bit array.
Attempts:
- I thought that I could convert it into long and than make the bit manipulation. However, long does not match my exact BitArray length, which results in errors later on when I apply bitwise operations on two BitArrays (my full requirements is (array1 |= array2 >> 20).
- I tried to convert the BitArray into byte[], do the manipulation and return it (see Bit shifting N bits):
public static byte[] ToBytesArray(this BitArray array, int startIndex, int count)
{
// Get the size of bytes needed to store all bytes
int bytesize = count / ByteLength;
// Any bit left over another byte is necessary
if (count % ByteLength > 0)
{
bytesize++;
}
// For the result
byte[] bytes = new byte[bytesize];
// Must init to good value, all zero bit byte has value zero
// Lowest significant bit has a place value of 1, each position to
// to the left doubles the value
byte value = 0;
byte significance = 1;
int bytepos = 0;
int bitpos = startIndex;
while (bitpos - startIndex < count)
{
// If the bit is set add its value to the byte
if (array[bitpos])
value += significance;
bitpos++;
if (bitpos % ByteLength == 0)
{
// A full byte has been processed, store it
// increase output buffer index and reset work values
bytes[bytepos] = value;
bytepos++;
value = 0;
significance = 1;
}
else
{
// Another bit processed, next has doubled value
significance *= 2;
}
}
return bytes;
}
public static BitArray ShiftLeft(this BitArray array, int bitcount)
{
byte[] value = array.ToBytesArray();
byte[] temp = new byte[value.Length];
if (bitcount >= 8)
{
Array.Copy(value, bitcount / 8, temp, 0, temp.Length - (bitcount / 8));
}
else
{
Array.Copy(value, temp, temp.Length);
}
if (bitcount % 8 != 0)
{
for (int i = 0; i < temp.Length; i++)
{
temp[i] <<= bitcount % 8;
if (i < temp.Length - 1)
{
temp[i] |= (byte)(temp[i + 1] >> 8 - bitcount % 8);
}
}
}
return new BitArray(temp);
}
However, byte's length is 8, which can't fit well with my length too. The result is 416 or 424 (another byte) instead of 421.
Finally, I tried the "primitive" way:
for (int i = 0; i < bitcount; i++)
{
var lastValue = array[0];
for (var j = 0; j < array.Length - 1; j++)
{
array[j] = array[j + 1];
}
array[array.Length - 1] = lastValue;
}
I also check up SO (e.g. BitArray - Shift bits) but nothing worked for me.
Any help will be very appreciated!
Still not 100% sure what's the issue. Here's a naive implementation:
void Main()
{
// Creates and initializes a BitArrays of size 7 (you have 421).
bool[] myBools = new bool[7] { true,false,false,true,true,false,true };
BitArray myBA1 = new BitArray(myBools );
PrintBitArray(myBA1); // 1001101
PrintBitArray(ShiftRight(myBA1)); // 0100110
PrintBitArray(ShiftLeft (myBA1)); // 0011010
}
BitArray ShiftRight(BitArray aSource) {
bool[] new_arr = new bool[( aSource.Count)];
for (int i = 0; i < aSource.Count -1; i++)
new_arr[i+1] = aSource[i];
return new BitArray(new_arr);
}
BitArray ShiftLeft(BitArray aSource) {
bool[] new_arr = new bool[( aSource.Count)];
for (int i = 0; i < aSource.Count -1; i++)
new_arr[i] = aSource[i+1];
return new BitArray(new_arr);
}
string PrintBitArray(BitArray aSource) {
StringBuilder sb = new StringBuilder();
foreach (var bit in aSource)
{
sb.Append( (bool)bit ? 1 : 0 );
}
return sb.ToString();
}
Note how bits are copied in the loops, and that the third PrintBitArray is done on the original input, not on the outcome of the second.
public static bool[] Left_shiftBitArray(bool[] Array, int count)
{
Array = BitArray_LRotat(Array, count);
for (int i=Array.GetLength(0)-1; i>=(Array.GetLength(0)-count); i--)
{
Array[i] = false;
}
return Array;
}
public static bool[] BitArray_LRotat(bool[] input, int x)
{
//bool [] temp= new bool[input.Length];
bool[] final = new bool[input.Length];
for (int i = input.Length; i > x; i--)
{
final[i - x - 1] = input[i - 1];
}
for (int i = x; i > 0; i--)
{
final[(input.Length) - i] = input[x - i];
}
return final;
}
I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');
I've written the following code in C# for obtaining the length of longest common subsequence of two texts given by use, but it doesn't work with large strings. Could you please help me. I'm really confused.
public Form1()
{
InitializeComponent();
}
public int lcs(char[] s1, char[] s2, int s1size, int s2size)
{
if (s1size == 0 || s2size == 0)
{
return 0;
}
else
{
if (s1[s1size - 1] == s2[s2size - 1])
{
return (lcs(s1, s2, s1size - 1, s2size - 1) + 1);
}
else
{
int x = lcs(s1, s2, s1size, s2size - 1);
int y = lcs(s1, s2, s1size - 1, s2size);
if (x > y)
{
return x;
}
else
return y;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string st1 = textBox2.Text.Trim(' ');
string st2 = textBox3.Text.Trim(' ');
char[] a = st1.ToCharArray();
char[] b = st2.ToCharArray();
int s1 = a.Length;
int s2 = b.Length;
textBox1.Text = lcs(a, b, s1, s2).ToString();
}
Here you are using the Recursion method. So it leads the program to occur performance problems as you mentioned.
Instead of recursion, use the dynamic programming approach.
Here is the C# Code.
public static void LCS(char[] str1, char[] str2)
{
int[,] l = new int[str1.Length, str2.Length];
int lcs = -1;
string substr = string.Empty;
int end = -1;
for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
if (str1[i] == str2[j])
{
if (i == 0 || j == 0)
{
l[i, j] = 1;
}
else
l[i, j] = l[i - 1, j - 1] + 1;
if (l[i, j] > lcs)
{
lcs = l[i, j];
end = i;
}
}
else
l[i, j] = 0;
}
}
for (int i = end - lcs + 1; i <= end; i++)
{
substr += str1[i];
}
Console.WriteLine("Longest Common SubString Length = {0}, Longest Common Substring = {1}", lcs, substr);
}
Here is a solution how to find the longest common substring in C#:
public static string GetLongestCommonSubstring(params string[] strings)
{
var commonSubstrings = new HashSet<string>(strings[0].GetSubstrings());
foreach (string str in strings.Skip(1))
{
commonSubstrings.IntersectWith(str.GetSubstrings());
if (commonSubstrings.Count == 0)
return string.Empty;
}
return commonSubstrings.OrderByDescending(s => s.Length).DefaultIfEmpty(string.Empty).First();
}
private static IEnumerable<string> GetSubstrings(this string str)
{
for (int c = 0; c < str.Length - 1; c++)
{
for (int cc = 1; c + cc <= str.Length; cc++)
{
yield return str.Substring(c, cc);
}
}
}
I found it here: http://www.snippetsource.net/Snippet/75/longest-common-substring
Just for fun, here is one example using Queue<T>:
string LongestCommonSubstring(params string[] strings)
{
return LongestCommonSubstring(strings[0], new Queue<string>(strings.Skip(1)));
}
string LongestCommonSubstring(string x, Queue<string> strings)
{
if (!strings.TryDequeue(out var y))
{
return x;
}
var output = string.Empty;
for (int i = 0; i < x.Length; i++)
{
for (int j = x.Length - i; j > -1; j--)
{
string common = x.Substring(i, j);
if (y.IndexOf(common) > -1 && common.Length > output.Length) output = common;
}
}
return LongestCommonSubstring(output, strings);
}
It's still using recursion though, but it's a nice example of Queue<T>.
I refactored the C++ code from Ashutosh Singh at https://iq.opengenus.org/longest-common-substring-using-rolling-hash/ to create a rolling hash approach in C# - this will find the substring in O(N * log(N)^2) time and O(N) space
using System;
using System.Collections.Generic;
public class RollingHash
{
private class RollingHashPowers
{
// _mod = prime modulus of polynomial hashing
// any prime number over a billion should suffice
internal const int _mod = (int)1e9 + 123;
// _hashBase = base (point of hashing)
// this should be a prime number larger than the number of characters used
// in my use case I am only interested in ASCII (256) characters
// for strings in languages using non-latin characters, this should be much larger
internal const long _hashBase = 257;
// _pow1 = powers of base modulo mod
internal readonly List<int> _pow1 = new List<int> { 1 };
// _pow2 = powers of base modulo 2^64
internal readonly List<long> _pow2 = new List<long> { 1L };
internal void EnsureLength(int length)
{
if (_pow1.Capacity < length)
{
_pow1.Capacity = _pow2.Capacity = length;
}
for (int currentIndx = _pow1.Count - 1; currentIndx < length; ++currentIndx)
{
_pow1.Add((int)(_pow1[currentIndx] * _hashBase % _mod));
_pow2.Add(_pow2[currentIndx] * _hashBase);
}
}
}
private class RollingHashedString
{
readonly RollingHashPowers _pows;
readonly int[] _pref1; // Hash on prefix modulo mod
readonly long[] _pref2; // Hash on prefix modulo 2^64
// Constructor from string:
internal RollingHashedString(RollingHashPowers pows, string s, bool caseInsensitive = false)
{
_pows = pows;
_pref1 = new int[s.Length + 1];
_pref2 = new long[s.Length + 1];
const long capAVal = 'A';
const long capZVal = 'Z';
const long aADif = 'a' - 'A';
unsafe
{
fixed (char* c = s)
{
// Fill arrays with polynomial hashes on prefix
for (int i = 0; i < s.Length; ++i)
{
long v = c[i];
if (caseInsensitive && capAVal <= v && v <= capZVal)
{
v += aADif;
}
_pref1[i + 1] = (int)((_pref1[i] + v * _pows._pow1[i]) % RollingHashPowers._mod);
_pref2[i + 1] = _pref2[i] + v * _pows._pow2[i];
}
}
}
}
// Rollingnomial hash of subsequence [pos, pos+len)
// If mxPow != 0, value automatically multiply on base in needed power.
// Finally base ^ mxPow
internal Tuple<int, long> Apply(int pos, int len, int mxPow = 0)
{
int hash1 = _pref1[pos + len] - _pref1[pos];
long hash2 = _pref2[pos + len] - _pref2[pos];
if (hash1 < 0)
{
hash1 += RollingHashPowers._mod;
}
if (mxPow != 0)
{
hash1 = (int)((long)hash1 * _pows._pow1[mxPow - (pos + len - 1)] % RollingHashPowers._mod);
hash2 *= _pows._pow2[mxPow - (pos + len - 1)];
}
return Tuple.Create(hash1, hash2);
}
}
private readonly RollingHashPowers _rhp;
public RollingHash(int longestLength = 0)
{
_rhp = new RollingHashPowers();
if (longestLength > 0)
{
_rhp.EnsureLength(longestLength);
}
}
public string FindCommonSubstring(string a, string b, bool caseInsensitive = false)
{
// Calculate max neede power of base:
int mxPow = Math.Max(a.Length, b.Length);
_rhp.EnsureLength(mxPow);
// Create hashing objects from strings:
RollingHashedString hash_a = new RollingHashedString(_rhp, a, caseInsensitive);
RollingHashedString hash_b = new RollingHashedString(_rhp, b, caseInsensitive);
// Binary search by length of same subsequence:
int pos = -1;
int low = 0;
int minLen = Math.Min(a.Length, b.Length);
int high = minLen + 1;
var tupleCompare = Comparer<Tuple<int, long>>.Default;
while (high - low > 1)
{
int mid = (low + high) / 2;
List<Tuple<int, long>> hashes = new List<Tuple<int, long>>(a.Length - mid + 1);
for (int i = 0; i + mid <= a.Length; ++i)
{
hashes.Add(hash_a.Apply(i, mid, mxPow));
}
hashes.Sort(tupleCompare);
int p = -1;
for (int i = 0; i + mid <= b.Length; ++i)
{
if (hashes.BinarySearch(hash_b.Apply(i, mid, mxPow), tupleCompare) >= 0)
{
p = i;
break;
}
}
if (p >= 0)
{
low = mid;
pos = p;
}
else
{
high = mid;
}
}
// Output answer:
return pos >= 0
? b.Substring(pos, low)
: string.Empty;
}
}
I`m trying to create a special counter in C# ... I mean the counter will be consisting of characters not numbers.
I have a char[] of size 3:
char[] str = new char[strSize];
int i = 0;
int tmpSize = strSize - 1;
int curr;
while(!isEqual(str,finalStr,strSize))
{
str[strSize] = element[i % element.Length];
i++;
if (str[strSize] == element[element.Length - 1])
{
int j = strSize - 1;
if (j > 0)
{
j--;
int tmpCntr = j+1;
curr = getCurrentID(str[tmpCntr]);
str[tmpCntr] = element[(curr + 1) % element.Length];
while (str[tmpCntr] == element[0] && (i % element.Length > 0) && tmpCntr < 0)
{
tmpCntr--;
curr = getCurrentID(str[tmpCntr]);
str[tmpCntr] = element[(curr + 1) % element.Length];
}
}
}
}
if the strSize < 3 the application works fine and gives accurate output. If the strSize >= 3, the application goes in infinite loop!
Need help.
if this is hard this way, I would need a way to create a numerical counter and I`ll work on it to suite my application.
You haven't shown what half of your methods or parameters are.
Personally I would take a different approach. I would use an iterator block to make it easy to return an IEnumerable<string>, and internally just keep an integer counter. Then you just need to write a method to convert a counter value and "alphabet of digits" into a string. Something like this:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
long max = (long) Math.Pow(digits.Length, digitCount);
for (long i = 0; i < max; i++)
{
yield return ConvertToString(i, digits, digitCount);
}
}
Another alternative is to do the same thing with LINQ, if a range of int is enough:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
int max = (int) Math.Pow(digits.Length, digitCount);
return Enumerable.Range(0, max)
.Select(i => ConvertToString(i, digits, digitCount));
}
In either case, you just iterate over the returned sequence to get appropriate counter values.
With those in place, you just need to implement ConvertToString - which would probably be something like this:
public static string ConvertToString(long value, string digits, int digitCount)
{
char[] chars = new char[digitCount];
for (int i = digitCount - 1 ; i >= 0; i--)
{
chars[i] = digits[(int)(value % digits.Length)];
value = value / digits.Length;
}
return new string(chars);
}
Here's a test program showing it all working:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
// Show the first 10 values
foreach (string value in Counter("ABCD", 3).Take(10))
{
Console.WriteLine(value);
}
}
public static IEnumerable<string> Counter(string digits, int digitCount)
{
long max = (long) Math.Pow(digits.Length, digitCount);
for (long i = 0; i < max; i++)
{
yield return ConvertToString(i, digits, digitCount);
}
}
public static string ConvertToString(long value,
string digits,
int digitCount)
{
char[] chars = new char[digitCount];
for (int i = digitCount - 1 ; i >= 0; i--)
{
chars[i] = digits[(int)(value % digits.Length)];
value = value / digits.Length;
}
return new string(chars);
}
}
Output:
AAA
AAB
AAC
AAD
ABA
ABB
ABC
ABD
ACA
ACB
I wrote this code in C# to encrypt a string with a key:
private static int Bin2Dec(string num)
{
int _num = 0;
for (int i = 0; i < num.Length; i++)
_num += (int)Math.Pow(2, num.Length - i - 1) * int.Parse(num[i].ToString());
return _num;
}
private static string Dec2Bin(int num)
{
if (num < 2) return num.ToString();
return Dec2Bin(num / 2) + (num % 2).ToString();
}
public static string StrXor(string str, string key)
{
string _str = "";
string _key = "";
string _xorStr = "";
string _temp = "";
for (int i = 0; i < str.Length; i++)
{
_temp = Dec2Bin(str[i]);
for (int j = 0; j < 8 - _temp.Length + 1; j++)
_temp = '0' + _temp;
_str += _temp;
}
for (int i = 0; i < key.Length; i++)
{
_temp = Dec2Bin(key[i]);
for (int j = 0; j < 8 - _temp.Length + 1; j++)
_temp = '0' + _temp;
_key += _temp;
}
while (_key.Length < _str.Length) _key += _key;
if (_key.Length > _str.Length) _key = _key.Substring(0, _str.Length);
for (int i = 0; i < _str.Length; i++)
if (_str[i] == _key[i]) { _xorStr += '0'; } else { _xorStr += '1'; }
_str = "";
for (int i = 0; i < _xorStr.Length; i += 8)
{
char _chr = (char)0;
_chr = (char)Bin2Dec(_xorStr.Substring(i, 8)); //ERROR : (Index and length must refer to a location within the string. Parameter name: length)
_str += _chr;
}
return _str;
}
The problem is that I always get error when I want to decrypt an encryted text with this code:
string enc_text = ENCRYPT.XORENC("abc","a"); // enc_text = " ♥☻"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); // ArgumentOutOfRangeException
Any clues?
If you have a character, a char, you can convert it to an integer, an int.
And then you can use the ^ operator to perform XOR on it. You don't appear to be using that operator at the moment, which might be the source of your problem.
string EncryptOrDecrypt(string text, string key)
{
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));
return result.ToString();
}
That kind of thing. Here's a longer version with comments that does the same thing in steps, to make it easier to learn from:
string EncryptOrDecrypt(string text, string key)
{
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
{
// take next character from string
char character = text[c];
// cast to a uint
uint charCode = (uint)character;
// figure out which character to take from the key
int keyPosition = c % key.Length; // use modulo to "wrap round"
// take the key character
char keyChar = key[keyPosition];
// cast it to a uint also
uint keyCode = (uint)keyChar;
// perform XOR on the two character codes
uint combinedCode = charCode ^ keyCode;
// cast back to a char
char combinedChar = (char)combinedCode;
// add to the result
result.Append(combineChar);
}
return result.ToString();
}
The short version is the same but with the intermediate variables removed, substituting expressions directly into where they're used.
// Code
public static byte[] EncryptOrDecrypt(byte[] text, byte[] key)
{
byte[] xor = new byte[text.Length];
for (int i = 0; i < text.Length; i++)
{
xor[i] = (byte)(text[i] ^ key[i % key.Length]);
}
return xor;
}
// Test
static void Main(string[] args){
string input;
byte[] inputBytes;
string inputKey;
byte[] key;
do
{
input = System.Console.ReadLine();
inputBytes = Encoding.Unicode.GetBytes(input);
inputKey = System.Console.ReadLine();
key = Encoding.Unicode.GetBytes(inputKey);
//byte[] key = { 0, 0 }; if key is 0, encryption will not happen
byte[] encryptedBytes = EncryptOrDecrypt(inputBytes, key);
string encryptedStr = Encoding.Unicode.GetString(encryptedBytes);
byte[] decryptedBytes = EncryptOrDecrypt(encryptedBytes, key);
string decryptedStr = Encoding.Unicode.GetString(decryptedBytes);
System.Console.WriteLine("Encrypted string:");
System.Console.WriteLine(encryptedStr);
System.Console.WriteLine("Decrypted string:");
System.Console.WriteLine(decryptedStr);
} while (input != "-1" && inputKey != "-1");
//test:
//pavle
//23
//Encrypted string:
//BRD_W
//Decrypted string:
//pavle
}
Here is some simple code to encrypt and decrypt
class CEncryption
{
public static string Encrypt(string strIn, string strKey)
{
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i++)
{
sbOut += String.Format("{0:00}", strIn[i] ^ strKey[i % strKey.Length]);
}
return sbOut;
}
public static string Decrypt(string strIn, string strKey)
{
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i += 2)
{
byte code = Convert.ToByte(strIn.Substring(i, 2));
sbOut += (char)(code ^ strKey[(i/2) % strKey.Length]);
}
return sbOut;
}
}