簡體   English   中英

如何使用PKCS 7和SHA算法在C#中創建數字簽名並進行驗證

[英]How to Create Digital Signature and Verify it in C# using PKCS 7 and SHA algorithm

我正在嘗試對xml文檔進行數字簽名,並使用公共密鑰和簽名的文檔來驗證原始xml文件的簽名。 我有一個Java代碼供參考。 我需要將Java代碼轉換為C#,而我擁有這樣的Java代碼:

   certList = new ArrayList<X509Certificate>();
   certList.add(signerCert);
   certStore = new JcaCertStore(certList);
   signedDataGenerator = new CMSSignedDataGenerator();
   ContentSigner sha2Signer = new JcaContentSignerBuilder("SHA512with" + privateKey.getAlgorithm()).build(privateKey);

   ignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(sha2Signer, signerCert));
   signedDataGenerator.addCertificates(certStore);
   CMSSignedData sigData = signedDataGenerator.generate(new CMSProcessableFile(inputXmlFile), false);
   signedBytes = sigData.getEncoded();

我已經將Java代碼轉換為C#,如下所示:

        X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        my.Open(OpenFlags.ReadOnly);
        // Find the certificate we’ll use to sign
        RSACryptoServiceProvider csp = null;
        foreach (X509Certificate2 cert in my.Certificates)
        {
            if (cert.Subject.Contains(certSubject))
            {
                // We found it.
                // Get its associated CSP and private key
                csp = (RSACryptoServiceProvider)cert.PrivateKey;                  
            }
        }
        if (csp == null)
        {
            throw new Exception("oppose no valid application was found");
        }
        // Hash the data
        SHA512Managed sha1 = new SHA512Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] data = encoding.GetBytes(text);
        byte[] hash = sha1.ComputeHash(data);
        // Sign the hash
        return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

自兩天以來,我一直在嘗試對其進行轉換,它正在生成符號字節數組,但無法進行驗證。 在驗證它引發嚴重的hash \\ r \\ n錯誤時,我將非常感謝您的協助。 我知道我在將Java代碼轉換為C#時出錯了。 我可以驗證代碼,但無法對文檔簽名

我已經使用System.Security.Cryptography.Pkcs庫生成了簽名,就像這樣

    public static byte[] Sign(byte[] data, X509Certificate2 certificate)
    {
        if (data == null)
            throw new ArgumentNullException("data");
        if (certificate == null)
            throw new ArgumentNullException("certificate");

        // setup the data to sign
        ContentInfo content = new ContentInfo(data);
        SignedCms signedCms = new SignedCms(content, false);
        CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
        // create the signature
        signedCms.ComputeSignature(signer);
        return signedCms.Encode();
    }

並像這樣驗證簽名

  private static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
    {
        CmsProcessable signedContent = null;
        CmsSignedData cmsSignedData = null;
        Org.BouncyCastle.X509.Store.IX509Store store = null;
        ICollection signers = null;
        bool verifiedStatus = false;
        try
        {
            //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
            signedContent = new CmsProcessableFile(contentFile);
            cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
            store = cmsSignedData.GetCertificates("Collection");//.getCertificates();
            IX509Store certStore = cmsSignedData.GetCertificates("Collection");
            signers = cmsSignedData.GetSignerInfos().GetSigners();
            foreach (var item in signers)
            {
                SignerInformation signer = (SignerInformation)item;
                var certCollection = certStore.GetMatches(signer.SignerID);
                IEnumerator iter = certCollection.GetEnumerator();
                iter.MoveNext();
                var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
                verifiedStatus = signer.Verify(cert.GetPublicKey());
            }

        }
        catch (Exception e)
        {
            throw e;
        }

        return verifiedStatus;
    }

它為我工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM