相关疑难解决方法(0)

使用RSA C#签名和验证签名

我最近发布了有关使用RSA加密大数据的问题,我最终完成了这一点,现在我继续使用用户的私钥实现签名并使用相应的公钥进行验证.但是,每当我比较签名数据和原始消息时,我基本上只会返回false.我希望你的一些人能看出我做错了什么.

这是代码:

public static string SignData(string message, RSAParameters privateKey)
    {
        //// The array to store the signed message in bytes
        byte[] signedBytes;
        using (var rsa = new RSACryptoServiceProvider())
        {
            //// Write the message to a byte array using UTF8 as the encoding.
            var encoder = new UTF8Encoding();
            byte[] originalData = encoder.GetBytes(message);

            try
            {
                //// Import the private key used for signing the message
                rsa.ImportParameters(privateKey);

                //// Sign the data, using SHA512 as the hashing algorithm 
                signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
            }
            catch …
Run Code Online (Sandbox Code Playgroud)

c# encoding signing rsa

49
推荐指数
1
解决办法
5万
查看次数

为什么我收到"指定的无效算法"异常

这是我的代码.

X509Certificate pXCert = new X509Certificate2(@"keyStore.p12", "password");
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)pXCert.PrivateKey;
string id = CryptoConfig.MapNameToOID("SHA256");
return csp.SignData(File.ReadAllBytes(filePath), id);
Run Code Online (Sandbox Code Playgroud)

在最后一行,我得到了例外:

System.Security.Cryptography.CryptographicException"指定的算法无效."

我究竟做错了什么?

更新:

id = 2.16.840.1.101.3.4.2.1

c# cryptography

17
推荐指数
4
解决办法
2万
查看次数

ASP.NET:使用文件中的公钥和私钥对URL进行签名

我想更新Google AMP缓存,因此我需要按此处所述签署一个网址.

我的主要问题:我正在努力获取我的证书/密钥,以及如何将它们包含在我的代码中.我找不到任何关于Windows和IIS的覆盖说明.

我一直在阅读这些帖子:

  1. 使用/ update-cache请求更新AMP页面
  2. 如何使用RSA和SHA256与.NET签署文件?

我不想使用第二篇文章中描述的计算机证书存储区.我宁愿在磁盘上使用公钥和私钥.从我的生产服务器IIS,我将我的证书导出到.pfx文件,然后我使用此站点底部的说明从中提取私钥和证书.server.key包含-----BEGIN RSA PRIVATE KEY-----,如果我使用它加载到privateCert下面代码中的变量抛出错误Cannot find the requested object.

我已经从我的SSL提供商得到: www_example_com.crt,www_example_com.p7b,的certificate code(见下文).

我采取的步骤:

  1. test-public-key.cer通过打开www_example.com.crt并使用Copy to file向导将其复制到base64编码的.cer文件来创建.
  2. certificate code收到了来自我的SSL提供商的文件test-private-key.cer.

当我运行以下代码时,我收到错误

你调用的对象是空的.

在线 key.FromXmlString(privateCert.PrivateKey.ToXmlString(True))

Dim publicCert As X509Certificate2 = New X509Certificate2("C:\temp\_certificates\test-public-key.cer")
Dim privateCert As X509Certificate2 = New X509Certificate2("C:\temp\_certificates\test-private-key.cer")

'Round-trip the key to XML and back, there might be a better way but …
Run Code Online (Sandbox Code Playgroud)

asp.net ssl rsa certificate google-amp

13
推荐指数
1
解决办法
649
查看次数

Google OAuth2服务帐户访问令牌请求会提供"无效请求"响应

我正在尝试通过服务器到服务器方法与我的应用程序启用的BigQuery API进行通信.

我已经在这个Google指南上勾选了我在J #中构建我的JWT的所有方框.

我对Base64Url编码了所有必要的东西.

但是,我从谷歌获得的唯一回应是400 Bad Request

"error" : "invalid_request"
Run Code Online (Sandbox Code Playgroud)

我从以下其他SO问题中确认了以下所有问题:

当我使用Fiddler时,我得到了相同的结果.错误消息令人沮丧地缺乏细节!我还能尝试什么?!这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        // certificate
        var certificate = new X509Certificate2(@"<Path to my certificate>.p12", "notasecret");

        // header
        var header = new { typ = "JWT", alg = "RS256" };

        // claimset
        var times = GetExpiryAndIssueDate();
        var claimset = new
        {
            iss = "<email address of the client id of my app>",
            scope = "https://www.googleapis.com/auth/bigquery",
            aud = "https://accounts.google.com/o/oauth2/token", …
Run Code Online (Sandbox Code Playgroud)

c# sha256 oauth-2.0 jwt google-bigquery

12
推荐指数
2
解决办法
5663
查看次数

Unity - 由于CryptographicException,无法发送HTTPS请求

我正在尝试向我的远程服务器发送https请求,但我总是遇到以下异常:

Exception: System.IO.IOException: The authentication or decryption has failed. ---> System.ArgumentException: certificate ---> System.Security.Cryptography.CryptographicException: Unsupported hash algorithm: 1.2.840.113549.1.1.11
  at Mono.Security.X509.X509Certificate.VerifySignature (System.Security.Cryptography.RSA rsa) [0x00000] in <filename unknown>:0 
  at Mono.Security.X509.X509Certificate.VerifySignature (System.Security.Cryptography.AsymmetricAlgorithm aa) [0x00000] in <filename unknown>:0 
  at System.Security.Cryptography.X509Certificates.X509Chain.IsSignedWith (System.Security.Cryptography.X509Certificates.X509Certificate2 signed, System.Security.Cryptography.AsymmetricAlgorithm pubkey) [0x00000] in <filename unknown>:0 
  at System.Security.Cryptography.X509Certificates.X509Chain.Process (Int32 n) [0x00000] in <filename unknown>:0 
  at System.Security.Cryptography.X509Certificates.X509Chain.ValidateChain (X509ChainStatusFlags flag) [0x00000] in <filename unknown>:0 
  at System.Security.Cryptography.X509Certificates.X509Chain.Build (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at System.Security.Cryptography.X509Certificates.X509Chain.Build …
Run Code Online (Sandbox Code Playgroud)

mono ssl https certificate unity-game-engine

6
推荐指数
1
解决办法
9692
查看次数

使用X509私钥在dotnet core v2(SHA256)中签名数据

我无法在dotnet core v2.0中重现某些加密功能。这是从.NET 4.5项目移植的代码

.NET 4.5代码

public byte[] SignData(byte[] dataToSign, X509Certificate2 certificate)
{
    var rsaCryptoServiceProvider = new RSACryptoServiceProvider();
    var xml = certificate.PrivateKey.ToXmlString(true);
    rsaCryptoServiceProvider.FromXmlString(xml);
    var signedBytes = rsaCryptoServiceProvider.SignData(dataToSign, CryptoConfig.MapNameToOID("SHA256"));
    return signedBytes;
}
Run Code Online (Sandbox Code Playgroud)

在dotnet核心中,ToXmlString()and FromXmlString()方法未实现,因此我使用了一个辅助类解决方法。除此之外,dotnet核心实现还可以工作,但是在给定相同的输入数据和证书的情况下,它会产生不同的结果。

dotnet core v2.0代码

public byte[] SignData(byte[] dataToSign, X509Certificate2 certificate)
{
    var rsaCryptoServiceProvider = new RSACryptoServiceProvider();
    var rsa = (RSA)certificate.PrivateKey;
    var xml = RSAHelper.ToXmlString(rsa);
    var parameters = RSAHelper.GetParametersFromXmlString(rsa, xml);
    rsaCryptoServiceProvider.ImportParameters(parameters);
    SHA256 alg = SHA256.Create();
    var signedBytes = rsaCryptoServiceProvider.SignData(dataToSign, alg);
    return signedBytes;
}
Run Code Online (Sandbox Code Playgroud)

编辑

在.NET 4.5代码库中,dotnet核心签名数据未通过签名验证检查。从理论上讲,它应该与什么签名方法没有什么区别,所以这应该起作用,但是没有作用。 …

.net c# cryptography .net-core

6
推荐指数
2
解决办法
5535
查看次数

如何(正确)使用 RSA 和 SHA256 和 .NET 验证文件?

我正在关注这个关于使用 .NET 进行数字签名/验证数据的精彩教程。我修改了该示例代码以使用 SHA256 并遇到“指定的算法无效”异常,这让我想到了这个关于在 .NET 4.0 中使用 SHA256 对数据进行签名的问题

该帖子中的一个答案帮助我弄清楚如何通过显式加载支持 SHA256 的加密提供程序而不依赖可导出的私钥来正确生成数字签名(请参阅以下方法底部的代码,其中构造了RSACryptoServiceProvider ):

static string mKeyContainerName;

static byte[] SignText(string text, string publicCertPath)
{
    // Access Personal (MY) certificate store of current user
    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);

    // Load the certificate we'll use to verify the signature from a file.
    X509Certificate2 publicCert = new X509Certificate2(publicCertPath);
    publicCert.Verify();
    string publicHash = publicCert.GetCertHashString();

    // Find the certificate we'll use …
Run Code Online (Sandbox Code Playgroud)

.net c# hash rsa digital-signature

5
推荐指数
1
解决办法
4696
查看次数

如何在C#中验证数字签名

我刚来这地方。

我正在学习C#中的数字签名。证书是在本文档之后生成的。我读过的其他文件:RSACngX509Certificate2

我正在使用 Windows 10 Pro 1809、.Net Core 2.1、VSCode。

    class Program
    {
        static void Main(string[] args)
        {
            var passwd = "password";

            // Get client certificate.
            var clientCertPath = @"./Certificates/test.pfx";
            var clientCert = new X509Certificate2(clientCertPath, passwd);

            // Get server certificate.
            var serverCertPath = @"./Certificates/test.cer";
            var serverCert = new X509Certificate2(serverCertPath);

            // Generate data.
            var translateResultData = BuildData();
            var content = String.Join('&', translateResultData.Select(p => String.Join('=', p.Key, p.Value)));

            // Sign
            var sign = SignatureUtil.Sign(data: content, clientCert: clientCert);
            // …
Run Code Online (Sandbox Code Playgroud)

.net c# .net-core

4
推荐指数
1
解决办法
2万
查看次数

在 C# 中使用私钥对数据进行签名

我需要使用算法 SHA1RSA ,Rsa 密钥长度 2048 和 64 基本编码,用一个私钥对一些数据进行签名。我的代码是这样的

string sPayload = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URI");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = WebRequestMethods.Http.Post;

using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    sPayload = "{\"id\":\"14123213213\"," +
                "\"uid\":\"teller\"," +
                "\"pwd\":\"abc123\"," +
                "\"apiKey\":\"2343243\"," +
                "\"agentRefNo\":\"234324324\"}";

    httpWebRequest.Headers.Add("SIGNATURE", Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(sPayload))));
    
    streamWriter.Write(sPayload);
    streamWriter.Flush();
    streamWriter.Close();
}

System.Net.ServicePointManager.Expect100Continue = false;

HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    string result = streamReader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

在标头名称签名中,我需要使用私钥传递签名数据(sPayload)。但是使用上面的代码会出现来自第三方的“无效签名”错误,我不确定加密部分是否正确。

httpWebRequest.Headers.Add("SIGNATURE", Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(sPayload))));
Run Code Online (Sandbox Code Playgroud)

第三方提供了一个证书(cert、sha1)和密钥。我应该将其参考代码吗?

c# cryptography rsa httprequest digital-signature

2
推荐指数
1
解决办法
3万
查看次数