Reputation: 1954
I'm making a simple custom encrypting in C#.NET, the encryption passes succesfully, but the decrypting goes wrong. The algorithm is very intuitive, but I don't know why it's decrypted wrong. Here is my code:
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);
}
And this is what I get when I encrypt: And this is when I decrypt: Thanks
Upvotes: 1
Views: 5673
Reputation: 700152
I see four problems with the code.
Here:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] + initial_text_bytes[secret_word_index]);
Use instead:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] + secret_word_bytes[secret_word_index]);
Encoding.UTF8.GetBytes
to try to decode the base-64 string.Here:
byte[] initial_text_bytes = Encoding.UTF8.GetBytes(text_criptat_tb.Text);
Use instead:
byte[] initial_text_bytes = Convert.FromBase64String(text_criptat_tb.Text);
Here:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] - initial_text_bytes[secret_word_index]);
Use instead:
encrypted_bytes[i] = (byte)(initial_text_bytes[i] - secret_word_bytes[secret_word_index]);
Convert.ToBase64String
to try to decode the UTF-8 data.Here:
initial_text_tb.Text = Convert.ToBase64String(encrypted_bytes);
Use instead:
initial_text_tb.Text = Encoding.UTF8.GetString(encrypted_bytes);
Upvotes: 5