help me with xor encryption in c#

Posted by x86shadow on Stack Overflow See other posts from Stack Overflow or by x86shadow
Published on 2010-03-28T11:13:11Z Indexed on 2010/03/28 11:23 UTC
Read the original article Hit count: 244

I wrote this code in c# to encrypt a text with a key :

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace ENCRYPT
{
    class XORENC
    {
        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 _dec = "";
            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]) { _dec += '0'; } else { _dec += '1'; }
            }
            _str = "";

            for (int i = 0; i < _dec.Length; i = i + 8)
            {
                char _chr = (char)0;
                _chr = (char)Bin2Dec(_dec.Substring(i, 8));
                _str += _chr;
            }

            return _str;
        }
    }
}

the problem is that I always get error when I want to decrypt an encryted text with this code. see the example below for more info :

string enc_text = ENCRYPT.XORENC("abc","a"); //enc_text = " ??"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); //ERROR

any one can help ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET