帮助我进行XOR加密

时间:2010-03-28 11:13:11

标签: c# encryption encryption-symmetric

我在C#中编写了此代码,用密钥加密字符串:

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;
}

问题是,当我想用​​这段代码解密加密文本时,我总是会收到错误:

string enc_text = ENCRYPT.XORENC("abc","a"); // enc_text = " ♥☻"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); // ArgumentOutOfRangeException

任何线索?

3 个答案:

答案 0 :(得分:46)

如果您有一个char字符,则可以将其转换为整数int

然后您可以使用^运算符对其执行XOR。您此刻似乎没有使用该运算符,这可能是您问题的根源。

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();
}

那种事。这是一个带有注释的较长版本,它们在步骤中执行相同的操作,以便更容易学习:

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();
}

短版本是相同的但删除了中间变量,直接将表达式替换为它们被使用的位置。

答案 1 :(得分:2)

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;
}

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
}

答案 2 :(得分:1)

以下是一些加密和解密的简单代码

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;
    }
 }