escribí este código en C#
para cifrar una cadena con una clave:Ayúdame con el cifrado XOR
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;
}
El problema es que siempre me sale error cuando quiero descifrar un texto encryted con este código:
string enc_text = ENCRYPT.XORENC("abc","a"); // enc_text = " ♥☻"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); // ArgumentOutOfRangeException
¿Alguna pista?
Todo lo que puedo decir es eh? :) Tal vez es un ejercicio educativo, pero no es necesario convertir los caracteres en cadenas, x o manualmente, y luego convertirlos a una cadena. Como lo demuestran las funciones de Dec2Bin y Bin2Dec, char se puede convertir ay desde ints con moldes, así que solo tome char de ambas cuerdas, aplique el operador '^' xor y ponga en una nueva cadena. – tyranid
Ayudaría si especifica qué error está recibiendo :) –
Además, es posible que desee utilizar StringBuilders en lugar de Strings. Las cadenas son inmutables (no se pueden cambiar), por lo que cosas como _str + = _temp; genera una nueva cadena cada vez, lo que hace que este método sea innecesariamente pesado/costoso. Use un StringBuilder y .Append (temp). –