Itext实现pdf文件Encryption

要实现证书加密pdf文件需要加入几个jar包,包括(iText-2.1.2u.jar,bcmail-jdk15-138.jar,bcprov-jdk16-139.jar,iTextAsian.jar等,看你自己的需要。注:本人用的jdk1.6,如果是用其他版本的jdk请去http://www.bouncycastle.org/latest_releases.html下载自己需要的包。),还有就是必须替换掉%JAVA_HOME%/jre/lib/securitylocal_policy.jar包。local_policy.jar,bcmail-jdk15-138.jar,bcprov-jdk16-139.jar在附件中可以下(为什么要换local_policy.jar具体也不是很清楚,好像是不使用sun公司提供的providers ,好像是sun提供加密限制了加密内容的length,这块不熟悉,如果有清楚的请不吝赐教。),iText-2.1.2u.jar,iTextAsian.jar这两个包可以在http://sourceforge.net/projects/itext/下载(附件中已有所有要用的包,还有一个测试证书). 注:必须是.cer的证书且支持加密。可以查看附件中的图片。
/**
     * Itext证书加密
     * 
     * @param originalFile
     *            pdf文件路径
     * @param encryptedFile
     *            加密后生成新的pdf文件路径
     * @param certFile
     *            证书路径
     * @param password
     *            证书密码
     * @param ownerPassWord
     *            所有者密码 
     */
    private static void certificateEncryption(String originalFile,
            String encryptedFile, String certFile, String password,
            String ownerPassWord) {
        PdfReader reader = null;
        InputStream is = null;
        PdfStamper stamper = null;
        try {

            // 添加providers (在%JAVA_HOME%/jre/lib/security/java.security 中可以找到sun提供的providers )
            Security.addProvider(new BouncyCastleProvider());
            // 如果原始文件已经加密 那么就要求提供ownerPassWord
            if (null == ownerPassWord || "".equals(ownerPassWord)) {
                reader = new PdfReader(originalFile);
            } else {
                reader = new PdfReader(originalFile, ownerPassWord.getBytes());
            }
            stamper = new PdfStamper(reader,
                    new FileOutputStream(encryptedFile));
            is = new FileInputStream(certFile);
            // SubjectPublicKeyInfo(由 X.509 标准定义)public key
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Certificate cert = cf.generateCertificate(is);
            Certificate[] certs = new Certificate[1];
            certs[0] = cert;

            int[] permissions = new int[7];
            permissions[0] = permissions[0] = PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_FILL_IN
            | PdfWriter.ALLOW_MODIFY_ANNOTATIONS | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS;
            // pdf文档加密
            stamper.setEncryption(certs, permissions,
                    PdfWriter.ENCRYPTION_AES_128);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
                //关闭流
                PdfUtil.close(reader);
                PdfUtil.close(is);
                PdfUtil.close(stamper);
        }
    }

你可能感兴趣的:(jdk,html,.net,Security,sun)