我在C#.NET中进行简单的自定义加密,加密成功通过,但解密出错了。该算法非常直观,但我不知道为什么它的解密错误。 这是我的代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
//Encrypting
byte[] initial_text_bytes = Encoding.UTF8.GetBytes(initial_text_tb.Text);
byte[] secret_word_bytes = Encoding.UTF8.GetBytes(secret_word_tb.Text);
byte[] encrypted_bytes = new byte[initial_text_bytes.Length];
int secret_word_index = 0;
for (int i=0; i < initial_text_bytes.Length; i++)
{
if (secret_word_index == secret_word_bytes.Length)
{
secret_word_index = 0;
}
encrypted_bytes[i] = (byte)(initial_text_bytes[i] + initial_text_bytes[secret_word_index]);
secret_word_index++;
}
// String s = Encoding.UTF8.GetString(encrypted_bytes);
//new String(Encoding.UTF8.GetChars(encrypted_bytes));
text_criptat_tb.Text = Convert.ToBase64String(encrypted_bytes);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
//Decrypting
byte[] initial_text_bytes = Encoding.UTF8.GetBytes(text_criptat_tb.Text);
byte[] secret_word_bytes = Encoding.UTF8.GetBytes(secret_word_tb.Text);
byte[] encrypted_bytes = new byte[initial_text_bytes.Length];
int secret_word_index = 0;
for (int i = 0; i < initial_text_bytes.Length; i++)
{
if (secret_word_index == secret_word_bytes.Length)
{
secret_word_index = 0;
}
encrypted_bytes[i] = (byte)(initial_text_bytes[i] - initial_text_bytes[secret_word_index]);
secret_word_index++;
}
// String s = new String(Encoding.UTF8.GetChars(encrypted_bytes));
initial_text_tb.Text = Convert.ToBase64String(encrypted_bytes);
}
这是我加密时得到的: 这是我解密的时候: 感谢
答案 0 :(得分:5)
我发现代码存在四个问题。
下面:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] + initial_text_bytes[secret_word_index]);
改为使用:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] + secret_word_bytes[secret_word_index]);
Encoding.UTF8.GetBytes
尝试解码base-64字符串。下面:
byte[] initial_text_bytes = Encoding.UTF8.GetBytes(text_criptat_tb.Text);
改为使用:
byte[] initial_text_bytes = Convert.FromBase64String(text_criptat_tb.Text);
下面:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] - initial_text_bytes[secret_word_index]);
改为使用:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] - secret_word_bytes[secret_word_index]);
Convert.ToBase64String
尝试解码UTF-8数据。下面:
initial_text_tb.Text = Convert.ToBase64String(encrypted_bytes);
改为使用:
initial_text_tb.Text = Encoding.UTF8.GetString(encrypted_bytes);