everybody!
I’m trying to digitally sign some data in C#. Everything goes without error but when I want to see the results of RSACryptoServiceProvider.SignHash , I get some strange results.
Here’s My code:
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindBySubjectName, "SOME NAME", true);
X509Certificate2Enumerator enumerator = certCollection.GetEnumerator();
X509Certificate2 x509 = null;
while (enumerator.MoveNext()){
x509 = enumerator.Current;
}
store.Close();
RSACryptoServiceProvider csp = null;
csp = (RSACryptoServiceProvider)x509.PrivateKey;
if (csp == null){
throw new Exception("Valid certificate was not found");
}
string sTestText = "SomeTestData";
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
SHA1Managed sha1 = new SHA1Managed();
ASCIIEncoding encoding2 = new System.Text.ASCIIEncoding();
byte[] data = encoding2.GetBytes(sTestText);
byte[] hash = sha1.ComputeHash(data);
Byte[] baSignedHash = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
string sSignedHash = System.Text.ASCIIEncoding.ASCII.GetString(baSignedHAsh);
Console.WriteLine("sSignedHash=" + sSignedHash );
I get this text:
sSignedHash=?H↨???C↑?X !??????sPotpisaniHash=J1??Q????7 ?G??D?5?=Dc?6C????♀??j?p?♠?♥?{♫??[i?↔?????◄??;?‼?????}Sx☺>VN?i6?☻’??▲f??t@?E?↕?▬??►k??v?’???☻ GX??}x@???)??F?7TP?♂&??
I’ve tried different encodings(UTF8, ect) but no luck. Does enyone know what could be the problem?
Yes. You’re trying to treat opaque binary data as if it were text. It’s not.
You could get a hex representation:
Or a base-64 representation:
It’s very important to understand the difference between “binary data which is actually encoded text data” (which is where
Encoding.GetStringcomes in) and “binary data which isn’t text” (e.g. image data, executable files, encrypted data, compressed data).