C# 无法查看数字签名哈希C的结果#
大家好 我正在尝试用C对一些数据进行数字签名。一切正常,但当我想看到rsacyptoserviceprovider.SignHash的结果时,我得到了一些奇怪的结果 这是我的密码:C# 无法查看数字签名哈希C的结果#,c#,C#,大家好 我正在尝试用C对一些数据进行数字签名。一切正常,但当我想看到rsacyptoserviceprovider.SignHash的结果时,我得到了一些奇怪的结果 这是我的密码: System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.Cur
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 );
我得到这段文字:
sSignedHash=?H↨???C↑?X!??????sPotpisaniHash=J1×Q×7×G×D×5=Dc×6C????♀??杰普?♠?♥?{♫??[我?↔?????◄??;?‼?????}Sx☺>VN?i6?☻'??▲f,t,E??↕?▬??►k??v?’???☻ GX???x@???F?7TP?♂&??
我尝试了不同的编码(UTF8,等),但没有运气。有人知道可能是什么问题吗
有人知道问题出在哪里吗
是的。你试图把不透明的二进制数据当作文本来对待。它不是
您可以得到十六进制表示:
string text = BitConverter.ToString(baSignedHash);
string text = Convert.ToBase64String(baSignedHash);
或base-64表示法:
string text = BitConverter.ToString(baSignedHash);
string text = Convert.ToBase64String(baSignedHash);
理解“实际编码为文本数据的二进制数据”(即
Encoding.GetString
的位置)和“非文本的二进制数据”(例如图像数据、可执行文件、加密数据、压缩数据)之间的区别非常重要.您不应该使用任何文本编码,因为哈希并不表示任何文本。它只是一堆字节
您应该使用十六进制编码或Base64编码将哈希转换为可读的内容
十六进制的优点是散列的每个字节对应于输出的两个字符
string sSignedHash = BitConverter.ToString(baSignedHash).Replace("-", "");
Base64的优点是它较短
string sSignedHash = Convert.ToBase64String(baSignedHash);
要对输入文本进行编码,我建议使用
新Utf8Encoding(false,true)
。这不会生成BOM表,当遇到无效输入时会引发异常,而不是默默地输出损坏的数据。谢谢Jon。这真的很有帮助。现在我明白了区别。:)