Create IExternalSignature with x509Certificate2 in C# and iText 7

后端 未结 1 1614
慢半拍i
慢半拍i 2020-12-18 15:02

I am testing the iText 7.1.2.0 library to sign pdf files, using a digital certificate or smart card (X509Certificate2) in a C # project. But I\'m getting this error when I t

相关标签:
1条回答
  • 2020-12-18 15:42

    I do not believe that class was ported to iText 7- it is just a wrapper class.

    You can see how to create a custom IExternalSignatureContainer in this example

    Note that the source for the iText 5 X509Certificate2Signature can be found here

    So something like this:

    public class X509Certificate2Signature: IExternalSignature {
        private String hashAlgorithm;
        private String encryptionAlgorithm;
        private X509Certificate2 certificate;
    
        public X509Certificate2Signature(X509Certificate2 certificate, String hashAlgorithm) {
            if (!certificate.HasPrivateKey)
                throw new ArgumentException("No private key.");
            this.certificate = certificate;
            this.hashAlgorithm = DigestAlgorithms.GetDigest(DigestAlgorithms.GetAllowedDigest(hashAlgorithm));
            if (certificate.PrivateKey is RSACryptoServiceProvider)
                encryptionAlgorithm = "RSA";
            else if (certificate.PrivateKey is DSACryptoServiceProvider)
                encryptionAlgorithm = "DSA";
            else
                throw new ArgumentException("Unknown encryption algorithm " + certificate.PrivateKey);
        }
    
        public virtual byte[] Sign(byte[] message) {
            if (certificate.PrivateKey is RSACryptoServiceProvider) {
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) certificate.PrivateKey;
                return rsa.SignData(message, hashAlgorithm);
            }
            else {
                DSACryptoServiceProvider dsa = (DSACryptoServiceProvider) certificate.PrivateKey;
                return dsa.SignData(message);
            }
        }
    
        public virtual String GetHashAlgorithm() {
            return hashAlgorithm;
        }
    
        public virtual String GetEncryptionAlgorithm() {
            return encryptionAlgorithm;
        }
    }
    

    Will replicate the class' function in iText 7. How to use the class is shown here in my first link, though you most likely will be using the signDetached() method instead of the signDeffered() method.

    0 讨论(0)
提交回复
热议问题