Aidez-moi avec le cryptage XOR
J'ai écrit ce code dans C#
pour chiffrer une chaîne avec une clé:
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;
}
Le problème est que je reçois toujours un message d'erreur quand je veux décrypter un encryted de texte avec ce code:
string enc_text = ENCRYPT.XORENC("abc","a"); //enc_text = " ♥☻"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); //ArgumentOutOfRangeException
Toute indices?
source d'informationauteur fardjad
Vous devez vous connecter pour publier un commentaire.
Si vous avez un personnage, un
char
vous pouvez convertir en un nombre entier, unint
.Et puis vous pouvez utiliser le
^
opérateur à effectuer XOR sur elle. Vous ne semblent pas être à l'aide de l'opérateur à l'heure actuelle, qui pourrait être la source de votre problème.Ce genre de chose. Voici une version plus longue avec des commentaires qui fait la même chose dans les étapes, pour le rendre plus facile d'apprendre à partir de:
La version courte est la même chose mais avec les variables intermédiaires supprimés, en substituant les expressions directement dans où ils sont utilisés.
Voici un code simple pour chiffrer et déchiffrer les