Я пытался найти множество решений в Интернете, но они не работали. Мне нужно подписать PDF-файл, извлекая хеш из PDF-файла и отправляя его в другую серверную службу, чтобы он подписал хэш и вернул его в подпись PDF. Пожалуйста, помогите мне! Ниже приведен мой код, где DataSigner — это API сторонней службы для вызова сервера для подписи хэша:
Я пытался найти множество решений в Интернете, но они не работали. Мне нужно подписать PDF-файл, извлекая хеш из PDF-файла и отправляя его в другую серверную службу, чтобы он подписал хэш и вернул его в подпись PDF. Пожалуйста, помогите мне! Ниже приведен мой код, где DataSigner — это API сторонней службы для вызова сервера для подписи хэша: [code] public class CreateSignature1 {
final DataSigner signer; private Certificate cert; private Certificate[] certificateChain;
public CreateSignature1(DataSigner signer) { this.signer = signer; }
/** * Signs the given PDF file. * * @param inFile the original PDF file */ public void signDocument(File inFile, Certificate cert, Certificate[] certChain) throws IOException, CertificateEncodingException, NoSuchAlgorithmException, OperatorCreationException, CMSException {
this.cert = cert;
// we're being given the certificate chain with public key setCertificateChain(certChain);
String name = inFile.getName(); String substring = name.substring(0, name.lastIndexOf('.'));
// retrieve signer certificate and its chain //X509Certificate cert = (X509Certificate) certificateChain[0];
// build signed attribute table generator and SignerInfo generator builder ESSCertIDv2 certid = new ESSCertIDv2( new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256), MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()) ); SigningCertificateV2 sigcert = new SigningCertificateV2(certid); Attribute attr = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(sigcert));
ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); AttributeTable atttributeTable = new AttributeTable(v); CMSAttributeTableGenerator attrGen = new DefaultSignedAttributeTableGenerator(atttributeTable);
return signedHash.get(0); } catch (Exception e) { throw new RuntimeException("Exception while signing", e); } }
@Override public OutputStream getOutputStream() { return stream; }
@Override public AlgorithmIdentifier getAlgorithmIdentifier() { return new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.1.1.11")); } };
// create the SignedData generator and execute CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(new JcaCertStore(Arrays.asList(certificateChain))); gen.addSignerInfoGenerator(sigb.build(contentSigner, new X509CertificateHolder(cert2)));
CMSTypedData msg = new CMSProcessableInputStream(externalSigning.getContent()); CMSSignedData signedData = gen.generate(msg, false);