Alexander
Alexander

Reputation: 97

Sign a file with a X509Certificate2 and private key

I would like to sign a file with a certificate. I wrote the following code but I get a "File content error" and also I always asked the private key. What did I do wrong? How can I send the private key? Thank you all.

        string cSerial = "0C4744041F40B761322124EB691C5F32";
        //Find my certificate with serial    
        X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);

        my.Open(OpenFlags.ReadOnly);

        System.Security.Cryptography.RSACryptoServiceProvider csp = null;

        foreach (X509Certificate2 cert in my.Certificates)
        {
            if (cert.SerialNumber.Trim() == cSerial)
            { csp = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey; }
        }
        //Here i have the certificate, it's ok.
        System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        //////////byte[] data = encoding.GetBytes("test.xml");
        byte[] data = File.ReadAllBytes("test.xml")
        byte[] hash = sha1.ComputeHash(data);
        byte[] aa = csp.SignHash(hash, System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"));
        File.WriteAllBytes("text.p7m", aa);

        my.Close();

Upvotes: 2

Views: 5429

Answers (1)

Alex Erygin
Alex Erygin

Reputation: 3230

You can solve this without Bouncy Castle, just using .NET

    /// <summary>
    ///     Make attached signature.
    /// </summary>
    public byte[] SignAttached(X509Certificate2 certificate, byte[] dataToSign)
    {
        ContentInfo contentInfo = new ContentInfo(dataToSign);
        SignedCms cms = new SignedCms(contentInfo, false);
        CmsSigner signer = new CmsSigner(certificate);
        cms.ComputeSignature(signer, false);
        return cms.Encode();
    }

    /// <summary>
    ///     Make detached signature.
    /// </summary>
    public byte[] SignDetached(X509Certificate2 certificate, byte[] dataToSign)
    {
        ContentInfo contentInfo = new ContentInfo(dataToSign);
        SignedCms cms = new SignedCms(contentInfo, true);
        CmsSigner signer = new CmsSigner(certificate);
        cms.ComputeSignature(signer, false);
        return cms.Encode();
    }

Upvotes: 3

Related Questions