<commit_before>/**
* OpenCPS PKI is the open source PKI Integration software
* Copyright (C) 2016-present OpenCPS community

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.pki;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Calendar;

import javax.imageio.ImageIO;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateUtil;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalBlankSignatureContainer;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignatureContainer;
import com.itextpdf.text.pdf.security.LtvTimestamp;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import com.itextpdf.text.pdf.security.TSAClient;
import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;

/**
 * Signer for pdf document
 * @author <NAME> <<EMAIL>>
 */
public class PdfSigner extends BaseSigner {

    /**
     * X509 certificate
     */
    private X509Certificate cert;

    /**
     * Signature image
     */
    private SignatureImage signatureImage;

    /**
     * signature field name
     */
    private String signatureFieldName;
    
    /**
     * Origin Pdf document file path
     */
    private String originFilePath;
    
    /**
     * Temporary Pdf document file path after generate hash key
     */
    private String tempFilePath;

    /**
     * Signed Pdf document file path
     */
    private String signedFilePath;
    
    /**
     * Sign date
     */
    private Calendar signDate;

    /**
     * Signature is visible
     */
    private Boolean isVisible;

    /**
     * Constructor
     *
     * @param filePath The path of pdf document
     * @param cert The certificate of user
     */
    public PdfSigner(String filePath, X509Certificate cert) {
        super();
        originFilePath = filePath;
        tempFilePath = Helper.stripFileExtension(filePath) + ".temp.pdf";
        signedFilePath = Helper.stripFileExtension(filePath) + ".signed.pdf";
        signDate = Calendar.getInstance();
        isVisible = true;
        this.cert= cert;
    }

    /**
     * (non-Javadoc)
     * @see org.opencps.pki.Signer#computeHash()
     */
    @Override
    public byte[] computeHash() {
        return computeHash(36.0f, 48.0f);
    }

    /**
     * Compute hash key with lower left corner of rectangle
     * @param llx lower left x
     * @param lly lower left y
     */
    public byte[] computeHash(float llx, float lly) {
        byte hash[] = null;
        int contentEstimated = 8192;
        try {
            PdfReader reader = new PdfReader(this.originFilePath);
            FileOutputStream os = new FileOutputStream(tempFilePath);
            PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            signatureFieldName = appearance.getNewSigName();
            TSAClient tsaClient = null;
            appearance.setCertificate(cert);
            String tsaUrl = CertificateUtil.getTSAURL(cert);
            if (tsaUrl != null) {
                tsaClient = new TSAClientBouncyCastle(tsaUrl);
            }
            if (tsaClient != null) {
                LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName);
                contentEstimated += 4096;
            }

            appearance.setSignDate(signDate);
            appearance.setLocation("OpenCPS PKI");
            appearance.setContact("OpenCPS PKI");
            if (!isVisible) {
                appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName);
            }
            else {
                if (signatureImage != null) {
                    appearance.setSignatureGraphic(signatureImage.getImage());
                    appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);

                    int signatureImageWidth = signatureImage.getBufferedImage().getWidth();
                    int signatureImageHeight = signatureImage.getBufferedImage().getHeight();
                    float urx = llx + signatureImageWidth;
                    float ury = lly + signatureImageHeight;
                    appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
                }
                else {
                    if (cert != null) {
                        CertificateInfo certInfo = new CertificateInfo(cert);
                        appearance.setLayer2Text(certInfo.getCommonName());
                    }
                    appearance.setVisibleSignature(new Rectangle(llx, lly, 144, 80), 1, signatureFieldName);
                }
            }

            ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
            MakeSignature.signExternalContainer(appearance, external, contentEstimated);
            <commit_msg>Add constructor and modify computeHash<commit_after>/**
* OpenCPS PKI is the open source PKI Integration software
* Copyright (C) 2016-present OpenCPS community

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.pki;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Calendar;

import javax.imageio.ImageIO;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateUtil;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalBlankSignatureContainer;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignatureContainer;
import com.itextpdf.text.pdf.security.LtvTimestamp;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import com.itextpdf.text.pdf.security.TSAClient;
import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;

/**
 * Signer for pdf document
 * @author <NAME> <<EMAIL>>
 */
public class PdfSigner extends BaseSigner {

    /**
     * X509 certificate
     */
    private X509Certificate cert;

    /**
     * Signature image
     */
    private SignatureImage signatureImage;

    /**
     * signature field name
     */
    private String signatureFieldName;
    
    /**
     * Origin Pdf document file path
     */
    private String originFilePath;
    
    /**
     * Temporary Pdf document file path after generate hash key
     */
    private String tempFilePath;

    /**
     * Signed Pdf document file path
     */
    private String signedFilePath;
    
    /**
     * Sign date
     */
    private Calendar signDate;

    /**
     * Signature is visible
     */
    private Boolean isVisible;

    /**
     * Constructor
     *
     * @param filePath The path of pdf document
     * @param cert The certificate of user
     */
    public PdfSigner(String filePath, X509Certificate cert) {
        super();
        originFilePath = filePath;
        tempFilePath = Helper.stripFileExtension(filePath) + ".temp.pdf";
        signedFilePath = Helper.stripFileExtension(filePath) + ".signed.pdf";
        isVisible = true;
        signDate = Calendar.getInstance();
        this.cert= cert;
    }

    /**
     * Constructor
     *
     * @param filePath The path of pdf document
     * @param cert The certificate of user
     * @param tempFilePath Temporary Pdf document file path after generate hash key
     * @param signedFilePath Signed Pdf document file path
     * @param isVisible Signature is visible
     */
    public PdfSigner(String filePath, X509Certificate cert, String tempFilePath, String signedFilePath, boolean isVisible) {
        super();
        originFilePath = filePath;
        this.tempFilePath = tempFilePath;
        this.signedFilePath = signedFilePath;
        this.isVisible = isVisible;
        signDate = Calendar.getInstance();
        this.cert= cert;
    }

    /**
     * (non-Javadoc)
     * @see org.opencps.pki.Signer#computeHash()
     */
    @Override
    public byte[] computeHash() {
        float llx = 36.0f;
        float lly = 48.0f;
        if (signatureImage != null) {
            int signatureImageWidth = signatureImage.getBufferedImage().getWidth();
            int signatureImageHeight = signatureImage.getBufferedImage().getHeight();
            float urx = llx + signatureImageWidth;
            float ury = lly + signatureImageHeight;
            return computeHash(llx, lly, urx, ury);
        }
        else {
            return computeHash(llx, lly, 144, 80);
        }
    }

    /**
     * Compute hash key with corner coordinates of rectangle
     *
     * @param llx lower left x
     * @param lly lower left y
     * @param urx upper right x
     * @param ury upper right y
     */
    public byte[] computeHash(float llx, float lly, float urx, float ury) {
        byte hash[] = null;
        int contentEstimated = 8192;
        try {
            PdfReader reader = new PdfReader(this.originFilePath);
            FileOutputStream os = new FileOutputStream(tempFilePath);
            PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            signatureFieldName = appearance.getNewSigName();
            TSAClient tsaClient = null;
            appearance.setCertificate(cert);
            String tsaUrl = CertificateUtil.getTSAURL(cert);
            if (tsaUrl != null) {
                tsaClient = new TSAClientBouncyCastle(tsaUrl);
            }
            if (tsaClient != null) {
                LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName);
                contentEstimated += 4096;
            }

            appearance.setSignDate(signDate);
            appearance.setLocation("OpenCPS PKI");
            appearance.setContact("OpenCPS PKI");
            if (!isVisible) {
                appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName);
            }
            else {
                if (signatureImage != null) {
                    appearance.setSignatureGraphic(signatureImage.getImage());
                    appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                    appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
                }
                else {
                    if (cert != null) {
                        CertificateInfo certInfo = new CertificateInfo(cert);
                        appearance.setLayer2Text(certInfo.getCommonName());
                    }
                    appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
                }
            }

            ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
            MakeSignature.signExternalContainer(appearance, external, contentEstimated);
            
{'fraction_non_alphanumeric': 0.087893864013267, 'fraction_numerical': 0.007311925222372983, 'mean_word_length': 2.576010781671159, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7481829', 'n_tokens_mistral': 3733, 'n_tokens_neox': 3611, 'n_words': 929}