C#USB eToken签名和验证问题

时间:2017-03-30 21:29:37

标签: c# cryptography rsacryptoserviceprovider

我有一个x509证书,其中包含存储在safenet usb令牌上的公钥和私钥。

我有一些我想签名的数据。我需要使用证书的公钥来验证签名。

使用我自己的自签名证书进行签名的终极代码:

RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

使用证书的公钥进行验证的代码:

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);

使用自签名证书可以正常工作。我得到的签名是256
字节。

使用此代码获取签名然后验证它,我只获得128字节签名并且验证失败:

CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);

验证与上述相同的代码。

我注意到我要使用的证书是令牌中的默认值。为什么我只返回128字节而不是256?我怀疑这就是为什么它不会验证。

我的csp中是否需要一些其他参数和设置?

由于

*根据评论更新*

很明显,当我指定csp.keyNumber =(int)KeyNumber.Signature时,我使用1024位 - 但这是令牌实际返回任何内容的唯一方法。即使令牌密钥大小为2048位且密钥规范为AT_KEYEXCHANGE。当我使用我认为实际上正确的交换密钥编号时,当我尝试计算签名时,系统会提示我登录,但后来我得到一个异常“参数无效”。所以,就我所见,我需要两件事之一:

1 - 如何使用公钥来验证签名使用1024位(没有令牌 - 我们需要在没有令牌的机器上验证)。

2 - 如何设置任何不正确的内容,以便我们可以通过异常 - 我认为这是更好的主意。

是否有人对我可以对此异常或可能导致异常的行为提出任何建议?

以下完整的例外情况:

HResult = -2147024809 消息=参数不正确。 堆栈跟踪

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)    在System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey,Int32 keyNumber,Int32 calgKey,Int32 calgHash,Byte [] hash,Int32 cbHash,ObjectHandleOnStack retSignature)    在System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey,Int32 keyNumber,Int32 calgKey,Int32 calgHash,Byte [] hash)    在System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte [] rgbHash,Int32 calgHash)    在System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte [] rgbHash,String str)    at TE.Program.Main(String [] args)在z:\ Work \ compusolve \ enctest \ TE \ TE \ Program.cs:第77行

2 个答案:

答案 0 :(得分:2)

答案是双重的。如果您使用其中一个设备,我发现在HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Cryptography \ Defaults \ Provider

下的注册表中

有3个不同的提供商。每个都具有相同的类型和甚至图像设置 - 使用的DLL。但在我的情况下,选择一个不同的Datakey RSP CSP,提供了基于2048位密钥的256字节签名。您还必须确保您使用的证书是令牌中的默认证书。在我的情况下,有两个不同的证书。我正在验证使用一个,但使用另一个签名。

测试客户端的完整源代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace TE
{
class Program
{
    static void Main(string[] args)
    {
        try
        {

            // these variables should be changed to math your installation

            // find CSP's in this windows registry key:  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider
            string TokenCSPName = "Datakey RSA CSP";
            string TokenCertificateName = "ACME Inc";
            string NonTokenCertificateName = "SelfSigned";
            string certLocation = "Token"; // change to something else to use self signed "Token" for token
            // the certificate on the token should be installed into the local users certificate store
            // tokens will not store or export the private key, only the public key


            // find the certificate we want to use - there's no recovery if the certificate is not found

            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection certificates = store.Certificates;
            X509Certificate2 certificate = new X509Certificate2();
            X509Certificate2 useCertificate = new X509Certificate2();
            if (certLocation == "Token")
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == TokenCertificateName)
                    {
                        for (int j = 0; j < extensions.Count; j++)
                        {
                            if ((extensions[j].KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
                            {
                                useCertificate = certificate;
                                j = extensions.Count + 1;
                            }

                        }

                    }
                }
            } else
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == NonTokenCertificateName)
                        useCertificate = certificate;
                }

            }
            CspParameters csp = new CspParameters(1, TokenCSPName);

            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
            csp.KeyNumber = (int)KeyNumber.Exchange;
            RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
            string SignatureString = "Data that is to be signed";
            byte[] plainTextBytes = Encoding.ASCII.GetBytes(SignatureString);
            bool Verified = false;
            using (SHA1CryptoServiceProvider shaM = new SHA1CryptoServiceProvider())
            {
                // hash the data to be signed - you can use signData and avoid the hashing if you like

                byte[] hash = shaM.ComputeHash(plainTextBytes);
                // sign the hash
                byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                // check your signature size here - if not 256 bytes then you may not be using the proper
                // crypto provider

                // Verify the signature with the hash

                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
                Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
                if (Verified)
                {
                    Console.WriteLine("Signature Verified");
                }
                else
                {
                    Console.WriteLine("Signature Failed Verification");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
  }
}

答案 1 :(得分:0)

我必须质疑你的断言它实际上是默认的密钥容器密钥(你可能在第一次运行代码时导致创建了一个密钥容器密钥,因为你没有断言UseExistingKey标志)。 / p>

假设证书在您的证书库中,请运行certutil -user -silent store my并找到证书条目并检查Key Container值:

================ Certificate 11 ================
Serial Number: 0123456789abcdeffedcba9876543210
Issuer: CN=Intermediate Certificate Authority
 NotBefore: 10/21/2016 7:26 AM
 NotAfter: 10/21/2017 7:26 AM
Subject: CN=bartonjs
Non-root Certificate
Template:
Cert Hash(sha1): 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14
  Key Container = le-Smartcard-987abcdf-6332-43-16531
  Provider = Microsoft Base Smart Card Crypto Provider

如果您复制/粘贴任何值并将其用作密钥容器名称,您的签名可能会以正确的大小开始。

(如果您的证书在机器商店而不是用户商店,请省略-user选项)