none
SHA1 with RSA in c#

    Question

  • Has anyone implemented SHA1 with RSA hashing with C#?  What I'm trying to do is calculate the <SignatureValue> element for the <SignedInfo> section of a SOAP envelope, but the result I get is different to the service provider I send the SOAP message to!  The Signature Algorithm isbe SHA1 with RSA (http://www.w3.org/2000/09/xmldsig#rsa-sha1), so I get a SHA1 hash value for my SignedInfo, and RSA encrypt the result (source code below).  Anyone have any ideas what I'm doing wrong?  Any suggestions gretefully received.

    In the code, I start off with a the SignedInfo section in text format in strSignedInfo, and get a result in strSignatureValue....

    strSignatureValue = getSHA1Hash(strSignedInfo);
    strSignatureValue = getRSAHash(strSignatureValue);


    static string getSHA1Hash(string PlainText)
    {
        SHA1 sha1Hasher = SHA1.Create();
        byte[] data = sha1Hasher.ComputeHash(Encoding.Default.GetBytes(PlainText));
        return Convert.ToBase64String(data);
    }


    private string getRSAHash(string PlainText)
    {
        string ResultString = "";
        string DigitalCertificateName = "C=IE, O=ad, OU=1234567, CN=f";
        X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        X509CertificateCollection collection = store.Certificates;
        foreach (X509Certificate cert in collection)
        {
            if (cert.Subject == DigitalCertificateName)
            {
                CspParameters CspParam;
                string publicXmlString = string.Empty;
                string privateXmlString = string.Empty;
                RSACryptoServiceProvider RsaCsp;
                RSACryptoServiceProvider RsaCsp2;
                UnicodeEncoding ByteConverter = new UnicodeEncoding();
                CspParam = new CspParameters();
                CspParam.KeyContainerName = cert.Subject; ;
                CspParam.Flags = CspProviderFlags.UseMachineKeyStore;
                byte[] encryptedString = ByteConverter.GetBytes(PlainText);
                RsaCsp = new RSACryptoServiceProvider(CspParam);
                //Get private key
                privateXmlString = RsaCsp.ToXmlString(true);
                 RsaCsp2 = new RSACryptoServiceProvider();
                RsaCsp2.FromXmlString(privateXmlString);
                encryptedString = RsaCsp2.Encrypt(System.Text.Encoding.Unicode.GetBytes(PlainText), false);
                ResultString = Convert.ToBase64String(encryptedString);
            }
        }
        store.Close();
        return ResultString;
    }

    Thanks,
    Fergus
    Thursday, April 02, 2009 4:06 PM

All replies