EaseRider

Untitled

Oct 24th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.39 KB | None | 0 0
  1. Index: src/main/java/org/apache/pdfbox/examples/signature/.java
  2. ===================================================================
  3. --- src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimestamp.java   (nonexistent)
  4. +++ src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimestamp.java   (working copy)
  5. @@ -0,0 +1,177 @@
  6. +/*
  7. + * Licensed to the Apache Software Foundation (ASF) under one or more
  8. + * contributor license agreements.  See the NOTICE file distributed with
  9. + * this work for additional information regarding copyright ownership.
  10. + * The ASF licenses this file to You under the Apache License, Version 2.0
  11. + * (the "License"); you may not use this file except in compliance with
  12. + * the License.  You may obtain a copy of the License at
  13. + *
  14. + *      http://www.apache.org/licenses/LICENSE-2.0
  15. + *
  16. + * Unless required by applicable law or agreed to in writing, software
  17. + * distributed under the License is distributed on an "AS IS" BASIS,
  18. + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. + * See the License for the specific language governing permissions and
  20. + * limitations under the License.
  21. + */
  22. +package org.apache.pdfbox.examples.signature;
  23. +
  24. +import java.io.File;
  25. +import java.io.FileNotFoundException;
  26. +import java.io.FileOutputStream;
  27. +import java.io.IOException;
  28. +import java.io.OutputStream;
  29. +import java.net.URL;
  30. +import java.security.GeneralSecurityException;
  31. +import java.security.MessageDigest;
  32. +
  33. +import org.apache.pdfbox.cos.COSName;
  34. +import org.apache.pdfbox.pdmodel.PDDocument;
  35. +import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
  36. +
  37. +/**
  38. + * An example for singing a PDF with bouncy castle. A keystore can be created with the java keytool, for example:
  39. + *
  40. + * {@code keytool -genkeypair -storepass 123456 -storetype pkcs12 -alias test -validity 365
  41. + *        -v -keyalg RSA -keystore keystore.p12 }
  42. + *
  43. + * @author Thomas Chojecki
  44. + * @author Vakhtang Koroghlishvili
  45. + * @author John Hewson
  46. + */
  47. +public class CreateSignedTimestamp extends CreateSignedTimestampBase
  48. +{
  49. +
  50. +    /**
  51. +     * Initialize the signature creator with a keystore and certficate password.
  52. +     */
  53. +    public CreateSignedTimestamp()
  54. +    {
  55. +        super();
  56. +    }
  57. +
  58. +    /**
  59. +     * Signs the given PDF file. Alters the original file on disk.
  60. +     *
  61. +     * @param file the PDF file to sign
  62. +     * @throws IOException if the file could not be read or written
  63. +     */
  64. +    public void signDetached(File file) throws IOException
  65. +    {
  66. +        signDetached(file, file, null);
  67. +    }
  68. +
  69. +    /**
  70. +     * Signs the given PDF file.
  71. +     *
  72. +     * @param inFile input PDF file
  73. +     * @param outFile output PDF file
  74. +     * @throws IOException if the input file could not be read
  75. +     */
  76. +    public void signDetached(File inFile, File outFile) throws IOException
  77. +    {
  78. +        signDetached(inFile, outFile, null);
  79. +    }
  80. +
  81. +    /**
  82. +     * Signs the given PDF file.
  83. +     *
  84. +     * @param inFile input PDF file
  85. +     * @param outFile output PDF file
  86. +     * @param tsaClient optional TSA client
  87. +     * @throws IOException if the input file could not be read
  88. +     */
  89. +    public void signDetached(File inFile, File outFile, TSAClient tsaClient) throws IOException
  90. +    {
  91. +        if (inFile == null || !inFile.exists())
  92. +        {
  93. +            throw new FileNotFoundException("Document for signing does not exist");
  94. +        }
  95. +
  96. +        FileOutputStream fos = new FileOutputStream(outFile);
  97. +
  98. +        // sign
  99. +        try (PDDocument doc = PDDocument.load(inFile))
  100. +        {
  101. +            signDetached(doc, fos, tsaClient);
  102. +        }
  103. +    }
  104. +
  105. +    public void signDetached(PDDocument document, OutputStream output, TSAClient tsaClient)
  106. +            throws IOException
  107. +    {
  108. +        setTsaClient(tsaClient);
  109. +
  110. +        int accessPermissions = getMDPPermission(document);
  111. +        if (accessPermissions == 1)
  112. +        {
  113. +            throw new IllegalStateException(
  114. +                    "No changes to the document are permitted due to DocMDP transform parameters dictionary");
  115. +        }
  116. +
  117. +        // create signature dictionary
  118. +        PDSignature signature = new PDSignature();
  119. +        signature.setType(COSName.DOC_TIME_STAMP);
  120. +        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
  121. +        signature.setSubFilter(COSName.getPDFName("ETSI.RFC3161"));//ETSI.RFC3161
  122. +        
  123. +        // the signing date, needed for valid signature
  124. +        //signature.setSignDate(Calendar.getInstance());
  125. +
  126. +        // Optional: certify
  127. +        if (accessPermissions == 0)
  128. +        {
  129. +            setMDPPermission(document, signature, 2);
  130. +        }
  131. +
  132. +        // register signature dictionary and sign interface
  133. +        document.addSignature(signature, this);
  134. +
  135. +        // write incremental (only for signing purpose)
  136. +        document.saveIncremental(output);
  137. +    }
  138. +
  139. +    public static void main(String[] args) throws IOException, GeneralSecurityException
  140. +    {
  141. +        if (args.length != 3)
  142. +        {
  143. +            usage();
  144. +            System.exit(1);
  145. +        }
  146. +
  147. +        String tsaUrl = null;
  148. +        if (args[1].equals("-tsa"))
  149. +        {
  150. +            tsaUrl = args[2];
  151. +        } else
  152. +        {
  153. +            usage();
  154. +            System.exit(1);
  155. +        }
  156. +
  157. +        // TSA client
  158. +        TSAClient tsaClient = null;
  159. +        if (tsaUrl != null)
  160. +        {
  161. +            MessageDigest digest = MessageDigest.getInstance("SHA-256");
  162. +            tsaClient = new TSAClient(new URL(tsaUrl), null, null, digest);
  163. +        }
  164. +
  165. +        // sign PDF
  166. +        CreateSignedTimestamp signing = new CreateSignedTimestamp();
  167. +
  168. +        File inFile = new File(args[0]);
  169. +        String name = inFile.getName();
  170. +        String substring = name.substring(0, name.lastIndexOf('.'));
  171. +
  172. +        File outFile = new File(inFile.getParent(), substring + "_timestamped.pdf");
  173. +        signing.signDetached(inFile, outFile, tsaClient);
  174. +    }
  175. +
  176. +    private static void usage()
  177. +    {
  178. +        System.err.println("usage: java " + CreateSignedTimestamp.class.getName() + " "
  179. +                + "<pdf_to_sign>\n" + "" + "options:\n"
  180. +                + "  -tsa <url>    sign timestamp using the given TSA server\n");
  181. +    }
  182. +}
  183.  
  184. Property changes on: src\main\java\org\apache\pdfbox\examples\signature\CreateSignedTimestamp.java
  185. ___________________________________________________________________
  186. Added: svn:mime-type
  187. ## -0,0 +1 ##
  188. +text/plain
  189. Index: src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimestampBase.java
  190. ===================================================================
  191. --- src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimestampBase.java   (nonexistent)
  192. +++ src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimestampBase.java   (working copy)
  193. @@ -0,0 +1,152 @@
  194. +/*
  195. + * Copyright 2015 The Apache Software Foundation.
  196. + *
  197. + * Licensed under the Apache License, Version 2.0 (the "License");
  198. + * you may not use this file except in compliance with the License.
  199. + * You may obtain a copy of the License at
  200. + *
  201. + *      http://www.apache.org/licenses/LICENSE-2.0
  202. + *
  203. + * Unless required by applicable law or agreed to in writing, software
  204. + * distributed under the License is distributed on an "AS IS" BASIS,
  205. + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. + * See the License for the specific language governing permissions and
  207. + * limitations under the License.
  208. + */
  209. +
  210. +package org.apache.pdfbox.examples.signature;
  211. +
  212. +import java.io.IOException;
  213. +import java.io.InputStream;
  214. +
  215. +import org.apache.pdfbox.cos.COSArray;
  216. +import org.apache.pdfbox.cos.COSBase;
  217. +import org.apache.pdfbox.cos.COSDictionary;
  218. +import org.apache.pdfbox.cos.COSName;
  219. +import org.apache.pdfbox.io.IOUtils;
  220. +import org.apache.pdfbox.pdmodel.PDDocument;
  221. +import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
  222. +import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
  223. +
  224. +public abstract class CreateSignedTimestampBase implements SignatureInterface
  225. +{
  226. +    private TSAClient tsaClient;
  227. +
  228. +    public void setTsaClient(TSAClient tsaClient)
  229. +    {
  230. +        this.tsaClient = tsaClient;
  231. +    }
  232. +
  233. +    public TSAClient getTsaClient()
  234. +    {
  235. +        return tsaClient;
  236. +    }
  237. +
  238. +    private byte[] getSignedTimeStampByte(InputStream content)
  239. +            throws IOException
  240. +    {
  241. +        return getTsaClient().getTimeStampToken(IOUtils.toByteArray(content));
  242. +    }
  243. +
  244. +    /**
  245. +     * SignatureInterface implementation.
  246. +     *
  247. +     * This method will be called from inside of the pdfbox and create the PKCS #7 signature. The given InputStream
  248. +     * contains the bytes that are given by the byte range.
  249. +     *
  250. +     * This method is for internal use only.
  251. +     *
  252. +     * Use your favorite cryptographic library to implement PKCS #7 signature creation.
  253. +     *
  254. +     * @throws IOException
  255. +     */
  256. +    @Override
  257. +    public byte[] sign(InputStream content) throws IOException
  258. +    {
  259. +        return getSignedTimeStampByte(content);
  260. +    }
  261. +
  262. +    /**
  263. +     * Get the access permissions granted for this document in the DocMDP transform parameters dictionary. Details are
  264. +     * described in the table "Entries in the DocMDP transform parameters dictionary" in the PDF specification.
  265. +     *
  266. +     * @param doc document.
  267. +     * @return the permission value. 0 means no DocMDP transform parameters dictionary exists. Other return values are
  268. +     * 1, 2 or 3. 2 is also returned if the DocMDP transform parameters dictionary is found but did not contain a /P
  269. +     * entry, or if the value is outside the valid range.
  270. +     */
  271. +    public int getMDPPermission(PDDocument doc)
  272. +    {
  273. +        COSBase base = doc.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.PERMS);
  274. +        if (base instanceof COSDictionary)
  275. +        {
  276. +            COSDictionary permsDict = (COSDictionary) base;
  277. +            base = permsDict.getDictionaryObject(COSName.DOCMDP);
  278. +            if (base instanceof COSDictionary)
  279. +            {
  280. +                COSDictionary signatureDict = (COSDictionary) base;
  281. +                base = signatureDict.getDictionaryObject("Reference");
  282. +                if (base instanceof COSArray)
  283. +                {
  284. +                    COSArray refArray = (COSArray) base;
  285. +                    for (int i = 0; i < refArray.size(); ++i)
  286. +                    {
  287. +                        base = refArray.getObject(i);
  288. +                        if (base instanceof COSDictionary)
  289. +                        {
  290. +                            COSDictionary sigRefDict = (COSDictionary) base;
  291. +                            if (COSName.DOCMDP
  292. +                                    .equals(sigRefDict.getDictionaryObject("TransformMethod")))
  293. +                            {
  294. +                                base = sigRefDict.getDictionaryObject("TransformParams");
  295. +                                if (base instanceof COSDictionary)
  296. +                                {
  297. +                                    COSDictionary transformDict = (COSDictionary) base;
  298. +                                    int accessPermissions = transformDict.getInt(COSName.P, 2);
  299. +                                    if (accessPermissions < 1 || accessPermissions > 3)
  300. +                                    {
  301. +                                        accessPermissions = 2;
  302. +                                    }
  303. +                                    return accessPermissions;
  304. +                                }
  305. +                            }
  306. +                        }
  307. +                    }
  308. +                }
  309. +            }
  310. +        }
  311. +        return 0;
  312. +    }
  313. +
  314. +    public void setMDPPermission(PDDocument doc, PDSignature signature, int accessPermissions)
  315. +    {
  316. +        COSDictionary sigDict = signature.getCOSObject();
  317. +
  318. +        // DocMDP specific stuff
  319. +        COSDictionary transformParameters = new COSDictionary();
  320. +        transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
  321. +        transformParameters.setInt(COSName.P, accessPermissions);
  322. +        transformParameters.setName(COSName.V, "1.2");
  323. +        transformParameters.setNeedToBeUpdated(true);
  324. +
  325. +        COSDictionary referenceDict = new COSDictionary();
  326. +        referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
  327. +        referenceDict.setItem("TransformMethod", COSName.getPDFName("DocMDP"));
  328. +        referenceDict.setItem("DigestMethod", COSName.getPDFName("SHA1"));
  329. +        referenceDict.setItem("TransformParams", transformParameters);
  330. +        referenceDict.setNeedToBeUpdated(true);
  331. +
  332. +        COSArray referenceArray = new COSArray();
  333. +        referenceArray.add(referenceDict);
  334. +        sigDict.setItem("Reference", referenceArray);
  335. +        referenceArray.setNeedToBeUpdated(true);
  336. +
  337. +        // Catalog
  338. +        COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
  339. +        COSDictionary permsDict = new COSDictionary();
  340. +        catalogDict.setItem(COSName.PERMS, permsDict);
  341. +        permsDict.setItem(COSName.DOCMDP, signature);
  342. +        catalogDict.setNeedToBeUpdated(true);
  343. +        permsDict.setNeedToBeUpdated(true);
  344. +    }
  345. +}
  346.  
  347. Property changes on: src\main\java\org\apache\pdfbox\examples\signature\CreateSignedTimestampBase.java
  348. ___________________________________________________________________
  349. Added: svn:mime-type
  350. ## -0,0 +1 ##
  351. +text/plain
Advertisement
Add Comment
Please, Sign In to add comment