如何使用 iText 对 pdf 进行数字签名?

2024-05-02

如何使用 iText 签署 pdf?我正在经历这个LINK http://itextpdf.sourceforge.net/howtosign.html但不了解 my_private_key.pfx。我真的需要数字签名证书吗?请澄清我。提前致谢。


希望这会帮助你

public class JPdfSign {

private static PrivateKey privateKey;

private static Certificate[] certificateChain;

private static ResourceBundle bundle = ResourceBundle.getBundle("strings");

private static String PRODUCTNAME = bundle.getString("productname");

private static String VERSION = bundle.getString("version");

private static String JAR_FILENAME = bundle.getString("jar-filename");

public static void main(String[] args) {
    // for (int i = 0; i < args.length; i++) {
    // System.out.println("arg[" + i + "] :" + args[i]);
    // }
    if (args.length < 2)
        showUsage();

    try {

        String pkcs12FileName = args[0].trim();
        String pdfInputFileName = args[1];
        String pdfOutputFileName = args[2];
        boolean usePKCS12 = !(pkcs12FileName.equals("-PKCS11"));

        System.out.println("");
        System.out.println("pdfInputFileName : " + pdfInputFileName);
        System.out.println("pdfOutputFileName: " + pdfOutputFileName);

        if (usePKCS12)
            readPrivateKeyFromPKCS12(pkcs12FileName);
        else
            readPrivateKeyFromPKCS11();

        PdfReader reader = null;
        try {
            reader = new PdfReader(pdfInputFileName);
        } catch (IOException e) {
            System.err
                    .println("An unknown error accoured while opening the input PDF file: \""
                            + pdfInputFileName + "\"");
            e.printStackTrace();
            System.exit(-1);
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {
            System.err
                    .println("An unknown error accoured while opening the output PDF file: \""
                            + pdfOutputFileName + "\"");
            e.printStackTrace();
            System.exit(-1);
        }
        PdfStamper stp = null;
        try {
            stp = PdfStamper.createSignature(reader, fout, '\0');
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            sap.setCrypto(privateKey, certificateChain, null,
                    PdfSignatureAppearance.WINCER_SIGNED);
            // sap.setReason("I'm the author");
            // sap.setLocation("Lisbon");
            // sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1,
            // null);
            stp.close();
        } catch (Exception e) {
            System.err
                    .println("An unknown error accoured while signing the PDF file:");
            e.printStackTrace();
            System.exit(-1);
        }
    } catch (KeyStoreException kse) {
        System.err
                .println("An unknown error accoured while initializing the KeyStore instance:");
        kse.printStackTrace();
        System.exit(-1);
    }
}

private static void readPrivateKeyFromPKCS11() throws KeyStoreException {
    // Initialize PKCS#11 provider from config file
    String configFileName = getConfigFilePath("pkcs11.cfg");

    Provider p = null;
    try {
        p = new SunPKCS11(configFileName);
        Security.addProvider(p);
    } catch (ProviderException e) {
        System.err
                .println("Unable to load PKCS#11 provider with config file: "
                        + configFileName);
        e.printStackTrace();
        System.exit(-1);
    }
    String pkcs11PIN = "000000";
    System.out.print("Please enter the smartcard pin: ");
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                System.in));
        pkcs11PIN = in.readLine();
        // System.out.println(pkcs11PIN);
        // System.out.println(pkcs11PIN.length());
    } catch (Exception e) {
        System.err
                .println("An unknown error accoured while reading the PIN:");
        e.printStackTrace();
        System.exit(-1);
    }
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("pkcs11", p);
        ks.load(null, pkcs11PIN.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#11 smartcard:");
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#11 smartcard:");
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#11 smartcard:");
        e.printStackTrace();
        System.exit(-1);
    }

    String alias = "";
    try {
        alias = (String) ks.aliases().nextElement();
        privateKey = (PrivateKey) ks.getKey(alias, pkcs11PIN.toCharArray());
    } catch (NoSuchElementException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        System.err
                .println("The selected PKCS#12 file does not contain any private keys.");
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        e.printStackTrace();
        System.exit(-1);
    }
    certificateChain = ks.getCertificateChain(alias);
}

protected static void readPrivateKeyFromPKCS12(String pkcs12FileName)
        throws KeyStoreException {
    String pkcs12Password = "";
    KeyStore ks = null;
    System.out.print("Please enter the password for \"" + pkcs12FileName
            + "\": ");
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                System.in));
        pkcs12Password = in.readLine();
    } catch (Exception e) {
        System.err
                .println("An unknown error accoured while reading the password:");
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        ks = KeyStore.getInstance("pkcs12");
        ks.load(new FileInputStream(pkcs12FileName), pkcs12Password
                .toCharArray());
    } catch (NoSuchAlgorithmException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#12 file:");
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#12 file:");
        e.printStackTrace();
        System.exit(-1);
    } catch (FileNotFoundException e) {
        System.err.println("Unable to open the PKCS#12 keystore file \""
                + pkcs12FileName + "\":");
        System.err
                .println("The file does not exists or missing read permission.");
        System.exit(-1);
    } catch (IOException e) {
        System.err
                .println("An unknown error accoured while reading the PKCS#12 file:");
        e.printStackTrace();
        System.exit(-1);
    }
    String alias = "";
    try {
        alias = (String) ks.aliases().nextElement();
        privateKey = (PrivateKey) ks.getKey(alias, pkcs12Password
                .toCharArray());
    } catch (NoSuchElementException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        System.err
                .println("The selected PKCS#12 file does not contain any private keys.");
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        System.err
                .println("An unknown error accoured while retrieving the private key:");
        e.printStackTrace();
        System.exit(-1);
    }
    certificateChain = ks.getCertificateChain(alias);
}

protected static String getConfigFilePath(String configFilename) {
    CodeSource source = JPdfSign.class.getProtectionDomain()
            .getCodeSource();
    URL url = source.getLocation();

    String jarPath = URLDecoder.decode(url.getFile());
    File f = new File(jarPath);
    try {
        jarPath = f.getCanonicalPath();
    } catch (IOException e) {
    }
    if (!f.isDirectory()) {
        f = new File(jarPath);
        jarPath = f.getParent();
    }
    System.out.println(jarPath);
    if (jarPath.length() > 0) {
        return jarPath + File.separator + configFilename;
    } else
        return configFilename;
}

public static void showUsage() {
    System.out.println("jPdfSign v" + VERSION
            + " by Jan Peter Stotz - [email protected] /cdn-cgi/l/email-protection\n");
    System.out.println(PRODUCTNAME + " usage:");
    System.out
            .println("\nFor using a PKCS#12 (.p12) file as signature certificate and private key source:");
    System.out.print("\tjava -jar " + JAR_FILENAME);
    System.out
            .println(" pkcs12FileName pdfInputFileName pdfOutputFileName");
    System.out
            .println("\nFor using a PKCS#11 smartcard as signature certificate and private key source:");
    System.out.print("\tjava -jar" + JAR_FILENAME);
    System.out.println(" -PKCS11 pdfInputFileName pdfOutputFileName");
    System.exit(0);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 iText 对 pdf 进行数字签名? 的相关文章

随机推荐

  • 从不同的程序集中动态加载类(具有自定义行为)?

    我们正在为少数客户构建应用程序 每个客户都有自己的要求以及类似的要求 我们还希望将所有代码保留在同一个应用程序中 而不是对其进行分支 并且 IF 不是一个好的选择 因为它会遍布各处 我计划为所有人开设基础课程 然后每个客户都会有自己的类 其
  • 即使更改内容后,Chrome 扩展程序弹出窗口也会重置

    在我的 chrome 扩展中 我必须从背景更改弹出 html 更改会影响然后 再次单击扩展图标后 将显示未更改的弹出窗口 为什么 每次您单击远离弹出窗口时 该窗口都会重置 解决此问题的一种方法是使用后台页面来存储会话数据 在 popup j
  • 如何从 Graph Explorer 查询另一个 Azure Active Directory 租户

    我正在使用 Azure Graph API 资源管理器 我想查询租户中的应用程序列表 我是tenant x 最初创建用户的位置 中的用户 也是tenant y 后来与我的用户创建的 中的管理员 据我所知 当我登录时 我直接进入原始租户 即t
  • 使用rapidjson设置浮点精度

    有没有办法控制使用rapidjson生成的JSON的输出精度 例如 writer String length writer Double 1 0 3 0 这会生成类似以下内容的内容 length 0 33333333 我发送了很多值 并且几
  • 如何使小部件溢出以使滚动条出现在 Qt 中?

    我的小部件的结构是 QWidget 定制为带有圆角边框的面板 要在边界内包含一个带有滚动条并带有边距的区域 然后我将其放入其中 QScrollArea 与 QVBoxLayout 垂直添加内容 然后我在其中添加一系列 标题间距为 0 的 Q
  • 从 C# 程序集中执行 JavaScript

    我想从 C 程序集中执行 JavaScript 代码 并将 JavaScript 代码的结果返回到调用 C 代码 定义我不想做的事情更容易 我并不是试图从我的代码隐藏中调用网页上的 JavaScript 函数 我不想加载 WebBrowse
  • 在 Windows 上使用 PHP 进行分叉/线程的最佳方法是什么?

    我有一个 php 脚本 用于检查许多 数千个 网站上的更新 有时 随着站点数量的增加 情况会更频繁 我在更新其中一个站点时会遇到执行超时 整个脚本都会付诸东流 我能想到的最好的想法是分叉每个更新 所以如果它死了 整体更新就会继续 从我收集到
  • subject.next 不在 ngOnInit 中触发

    有谁知道为什么这段代码 从主题初始化一个值 不起作用 是否存在错误或设计使然 我究竟做错了什么 ts import Component OnInit from angular core import Subject from rxjs Co
  • 载波扩展白名单不工作

    这是一个类似的案例 但没有解决方案CarrierWave extension white list 似乎不起作用 https stackoverflow com questions 11348510 carrierwave extensio
  • 使用 JDK8 时,LogManager.getLogger 会使应用程序停止大约 10-30 秒:

    更新 1 我做了更多测试 删除了大部分库并注释掉了库特定代码 导致了相同的行为 这让我得出结论 这个问题不是 直接 由这些库引起的 但似乎是我的一个普遍问题代码和 或设置 这里的主要问题是我不明白为什么它在从 Eclipse 内部启动时运行
  • 我的 on_member_join 事件不起作用。我尝试了意图,但它给出了这个错误

    考虑 最近一次通话最后 文件 randomgg py 第 1271 行 位于 u003cmodule u003e 中客户端 运行 令牌 文件 usr local lib python3 8 site packages discord cli
  • 如何在 javadoc 编译期间抑制警告(代码库范围内)?

    我被困在一个遗留的 Java 代码库中 当你编译它时 它有数千个警告 我很想真正修复所有这些警告的来源 但不幸的是 目前在我的公司这不是一个选择 负责人认为 制造可产生收入的新产品 等其他事情被认为是更优先的事情 想象一下 现在 如果不是因
  • 用子矩阵替换 numpy 矩阵元素

    鉴于我有一个索引方阵 例如 idxs np array 1 1 0 1 以及彼此大小相同的方阵数组 不一定与idxs mats array 0 0 0 0 5 1 0 3 1 1 我想替换每个索引idxs对应的矩阵为mats 得到 arra
  • Docker 中的 Keycloak“无法将代码转换为令牌”

    我正在 Docker compose 网络中运行 Keycloak keycloak Security Proxy 和 ui 应用程序 当我尝试访问该网页时 我得到一个可以使用的登录页面 但我没有成功重定向 而是收到以下错误 gt Aug
  • 控制台应用程序的 log4net 配置

    谁能建议如何为控制台应用程序配置 log4net 或者至少如何 在哪里捕捉Application Start事件 看来此时需要一些电话 提前致谢 尝试写作 assembly log4net Config XmlConfigurator Wa
  • Vimscript 检查当前缓冲区是否有未保存的更改

    我目前已设置状态行 使其在插入模式下为橙色 否则为白色 如果文件有任何未保存的更改 我想让它在我回到正常模式时变成另一种颜色 因为我经常在兔子洞里走一会儿 想知道为什么我的更改没有生效 小 还不够打我的脸 我找不到任何以 buf 开头且看起
  • 如何将零件逐一添加到闪亮的图表中

    我正在尝试为我的统计课程制作一些演示 除此之外 我想展示所涉及的逐步过程 对于我正在寻找的简化示例 请考虑以下小玩具 R 函数 toyPlot lt function x lt 1 100 100 y lt x rnorm 100 0 0
  • 当前不会命中切换断点。断点已设置但尚未绑定

    我在 Visual Studio 2019 中创建了一个 asp net core mvc 项目 我看到其他人讨论这个问题并做了以下工作 调试模式设置为调试 而不是发布 删除了 bin 和 obj 文件夹 清理并重建解决方案 删除所有断点
  • python 中的多线程:大多数时候它真的性能高效吗?

    据我所知 驱动编程的是性能因素multi threading在大多数情况下 但不是全部 无论 Java 还是 Python 我正在读这个启发性文章 https stackoverflow com questions 265687 why t
  • 如何使用 iText 对 pdf 进行数字签名?

    如何使用 iText 签署 pdf 我正在经历这个LINK http itextpdf sourceforge net howtosign html但不了解 my private key pfx 我真的需要数字签名证书吗 请澄清我 提前致谢