如何创建SHA1WithRSA签名

时间:2018-10-04 14:24:38

标签: c# .net

我有一个Java签名生成器:

private static String getPvtKeyFromConfig = "merchantPvtKey";
private static String getPubKeyFromConfig = "merchantPubKey";
private static String getSaltFromConfig = "merchant_salt";
public  static void main(String[] args) throws Exception {   
    // Generate Signature    
    String uniqueId="ab123";
    byte[] data = Base64.decodeBase64(uniqueId);
    java.security.Signature sig =java.security.Signature.getInstance("SHA1WithRSA");        
    sig.initSign(getPrivateFromSpec(getPvtKeyFromConfig));
    sig.update(data);  
    byte[] signatureBytes = sig.sign(); 
    System.out.println("Signature for uniqueId - "+uniqueId+": "+ Base64.encodeBase64String(signatureBytes));
}

如何在C#中做到这一点?

1 个答案:

答案 0 :(得分:1)

我认为这就是您想要的:

static byte[] Sign(string text, string certSubject)
{
    // Access a store
    using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
        store.Open(OpenFlags.ReadOnly);

        // Find the certificate used to sign
        RSACryptoServiceProvider provider = null;
        foreach (X509Certificate2 cert in store.Certificates)
        {
            if (cert.Subject.Contains(certSubject))
            {
                // Get its associated CSP and private key
                provider = (RSACryptoServiceProvider)cert.PrivateKey;
                break;
            }
        }

        if (provider == null)
            throw new Exception("Certificate not found.");

        // Hash the data
        var hash = HashText(text);

        // Sign the hash
        var signature = provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
        return signature;
    }                
}


static bool Verify(string text, byte[] signature, string certPath)
{

    // Load the certificate used to verify the signature
    X509Certificate2 certificate = new X509Certificate2(certPath);

    // Get its associated provider and public key
    RSACryptoServiceProvider provider = (RSACryptoServiceProvider)certificate.PublicKey.Key;

    // Hash the data
    var hash = HashText(text);

    // Verify the signature with the hash
    var result = provider.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
    return result;
}

static byte[] HashText(string text)
{
    SHA1Managed sha1Hasher = new SHA1Managed();
    UnicodeEncoding encoding = new UnicodeEncoding();
    byte[] data = encoding.GetBytes(text);
    byte[] hash = sha1Hasher.ComputeHash(data);
    return hash;
}

样品用量:

var signature = Sign("To be or not to be, that is the question.", "CN=some_cert");
var result = Verify("To be or not to be, that is the question.", signature, "C:\\temp\\some_cert.cer");
Console.WriteLine("Verified: {0}", result);