Rami W.
Rami W.

Reputation: 81

Digest a message and best encoding from byte[] to String

Situation

I am using Bouncy Castle API in my C# project. I need to hash a String using Org.BouncyCastle.Crypto

My Sample

String msg = "Message to Hash"; 
MD5Digest dig = new MD5Digest(); 

byte[] msgBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(msg);
dig.BlockUpdate(msgBytes, 0, msgBytes.Length);
byte[] result = new byte[dig.GetDigestSize()]; 
dig.DoFinal(result, 0);
Console.WriteLine("{0}", Convert.ToBase64String(result));

As as result i got a hash looking like XasdDdflk7ghXi8azuhe==

Questions

  1. I got always the "==" in the end of any different message. Is it normal ?
  2. I tried to convert from byte[] to String using System.Text.ASCIIEncoding.ASCII.GetString() but I get symbols like "!?..." I want to avoid the "==" in the end. What should I do ? changing Encoder ?

Upvotes: 1

Views: 3079

Answers (2)

BS_Erwin
BS_Erwin

Reputation: 1

You probably want a hex representation of the digest and not a base64 one.

return BitConverter.ToString(result).Replace("-", string.Empty); 

And you will end up with:

b3b438c3b84574bb4069e0d667a18503f82fedb5

Upvotes: 0

user47589
user47589

Reputation:

The == is a result of base 64 padding the result. You can strip them if you so desire.

Upvotes: 2

Related Questions