001    /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
002     *
003     * Redistribution and use in  source and binary forms, with or without 
004     * modification, are permitted  provided that the following conditions are met:
005     *
006     * 1. Redistributions of  source code must retain the above copyright notice,
007     *    this list of conditions and the following disclaimer.
008     *
009     * 2. Redistributions in  binary form must reproduce the above copyright notice,
010     *    this list of conditions and the following disclaimer in the documentation
011     *    and/or other materials provided with the distribution.
012     *  
013     * 3. The end-user documentation included with the redistribution, if any, must
014     *    include the following acknowledgment:
015     * 
016     *    "This product includes software developed by IAIK of Graz University of
017     *     Technology."
018     * 
019     *    Alternately, this acknowledgment may appear in the software itself, if 
020     *    and wherever such third-party acknowledgments normally appear.
021     *  
022     * 4. The names "Graz University of Technology" and "IAIK of Graz University of
023     *    Technology" must not be used to endorse or promote products derived from 
024     *    this software without prior written permission.
025     *  
026     * 5. Products derived from this software may not be called 
027     *    "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior 
028     *    written permission of Graz University of Technology.
029     *  
030     *  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
031     *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
032     *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
033     *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
034     *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
035     *  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
036     *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
037     *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
038     *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
039     *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
040     *  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
041     *  POSSIBILITY  OF SUCH DAMAGE.
042     */
043    
044    package demo.pkcs.pkcs11;
045    
046    import java.io.BufferedReader;
047    import java.io.ByteArrayOutputStream;
048    import java.io.FileInputStream;
049    import java.io.FileOutputStream;
050    import java.io.InputStream;
051    import java.io.InputStreamReader;
052    import java.io.OutputStream;
053    import java.io.PrintWriter;
054    import java.security.MessageDigest;
055    import java.util.Arrays;
056    import java.util.List;
057    
058    import iaik.asn1.ASN;
059    import iaik.asn1.ASN1Object;
060    import iaik.asn1.DerCoder;
061    import iaik.asn1.OCTET_STRING;
062    import iaik.asn1.ObjectID;
063    import iaik.asn1.structures.AlgorithmID;
064    import iaik.asn1.structures.Attribute;
065    import iaik.asn1.structures.ChoiceOfTime;
066    import iaik.pkcs.pkcs11.Mechanism;
067    import iaik.pkcs.pkcs11.MechanismInfo;
068    import iaik.pkcs.pkcs11.Module;
069    import iaik.pkcs.pkcs11.Session;
070    import iaik.pkcs.pkcs11.Token;
071    import iaik.pkcs.pkcs11.objects.PrivateKey;
072    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
073    import iaik.pkcs.pkcs11.objects.X509PublicKeyCertificate;
074    import iaik.pkcs.pkcs7.DigestInfo;
075    import iaik.pkcs.pkcs7.IssuerAndSerialNumber;
076    import iaik.pkcs.pkcs7.SignedData;
077    import iaik.pkcs.pkcs7.SignerInfo;
078    import iaik.x509.X509Certificate;
079    
080    
081    
082    /**
083     * Creates a signature on a token. The hash is calculated outside the token.
084     * The signed data and the signature are encoded into a PKCS#7 signed data
085     * object. This implementation just uses raw RSA.
086     *
087     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
088     * @version 0.1
089     * @invariants
090     */
091    public class SignPKCS7 {
092    
093      static PrintWriter output_;
094    
095      static BufferedReader input_;
096    
097      static {
098        try {
099          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
100          output_ = new PrintWriter(System.out, true);
101          input_ = new BufferedReader(new InputStreamReader(System.in));
102        } catch (Throwable thr) {
103          thr.printStackTrace();
104          output_ = new PrintWriter(System.out, true);
105          input_ = new BufferedReader(new InputStreamReader(System.in));
106        }
107      }
108    
109      public static void main(String[] args) {
110        if (args.length != 3) {
111          printUsage();
112          System.exit(1);
113        }
114    
115        try {
116    
117          Module pkcs11Module = Module.getInstance(args[0]);
118          pkcs11Module.initialize(null);
119    
120          Token token = Util.selectToken(pkcs11Module, output_, input_);
121          if (token == null) {
122            output_.println("We have no token to proceed. Finished.");
123            output_.flush();
124            System.exit(0);
125          }
126    
127          List supportedMechanisms = Arrays.asList(token.getMechanismList());
128          if (!supportedMechanisms.contains(Mechanism.RSA_PKCS)) {
129            output_.print("This token does not support raw RSA signing!");
130            output_.flush();
131            System.exit(0);
132          } else {
133            MechanismInfo rsaMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS);
134            if (!rsaMechanismInfo.isSign()) {
135              output_.print("This token does not support RSA signing according to PKCS!");
136              output_.flush();
137              System.exit(0);
138            }
139          }
140    
141          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_);
142    
143          // first we search for private RSA keys that we can use for signing
144          RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();
145          privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
146    
147          KeyAndCertificate selectedSignatureKeyAndCertificate =
148              Util.selectKeyAndCertificate(session, privateSignatureKeyTemplate, output_, input_);
149          if (selectedSignatureKeyAndCertificate == null) {
150            output_.println("We have no signature key to proceed. Finished.");
151            output_.flush();
152            System.exit(0);
153          }
154    
155          PrivateKey selectedSignatureKey = (PrivateKey) selectedSignatureKeyAndCertificate.getKey();
156          X509PublicKeyCertificate pkcs11SignerCertificate = selectedSignatureKeyAndCertificate.getCertificate();
157          X509Certificate signerCertificate = (pkcs11SignerCertificate != null)
158                                              ? new X509Certificate(pkcs11SignerCertificate.getValue().getByteArrayValue())
159                                              : null;
160    
161          // here the interesting code starts
162    
163          output_.println("################################################################################");
164          output_.println("signing data from file: " + args[1]);
165    
166          InputStream dataInputStream = new FileInputStream(args[1]);
167    
168          // we do digesting outside the card, because some cards do not support on-card hashing
169          MessageDigest digestEngine = MessageDigest.getInstance("SHA-1");
170    
171          // we buffer the content to have it after hashing for the PKCS#7 content
172          ByteArrayOutputStream contentBuffer = new ByteArrayOutputStream();
173          byte[] dataBuffer = new byte[1024];
174          byte[] helpBuffer;
175          int bytesRead;
176    
177          // feed all data from the input stream to the message digest
178          while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
179            // hash the data
180            digestEngine.update(dataBuffer, 0, bytesRead);
181            // and buffer the data
182            contentBuffer.write(dataBuffer, 0, bytesRead);
183          }
184          byte[] contentHash = digestEngine.digest();
185          contentBuffer.close();
186    
187          // create the SignedData
188          SignedData signedData = new SignedData(contentBuffer.toByteArray(), SignedData.IMPLICIT);
189          // set the certificates
190          signedData.setCertificates(new X509Certificate[] { signerCertificate });
191    
192          // create a new SignerInfo
193          SignerInfo signerInfo = new SignerInfo(new IssuerAndSerialNumber(signerCertificate), AlgorithmID.sha1, null);
194    
195          // define the authenticated attributes
196          iaik.asn1.structures.Attribute[] authenticatedAttributes = {
197            new Attribute(ObjectID.contentType, new ASN1Object[] {ObjectID.pkcs7_data}),
198            new Attribute(ObjectID.signingTime, new ASN1Object[] {new ChoiceOfTime().toASN1Object()}),
199            new Attribute(ObjectID.messageDigest, new ASN1Object[] {new OCTET_STRING(contentHash)})
200          };
201          // set the authenticated attributes
202          signerInfo.setAuthenticatedAttributes(authenticatedAttributes);
203    
204          // encode the authenticated attributes, which is the data that we must sign
205          byte[] toBeSigned = DerCoder.encode(ASN.createSetOf(authenticatedAttributes, true));
206    
207    
208          // we do digesting outside the card, because some cards do not support on-card hashing
209          // we can use the digest engine from above
210          byte[] hashToBeSigned = digestEngine.digest(toBeSigned);
211    
212          // according to PKCS#11 building the DigestInfo structure must be done off-card
213          DigestInfo digestInfoEngine = new DigestInfo(AlgorithmID.sha1, hashToBeSigned);
214    
215          byte[] toBeEncrypted = digestInfoEngine.toByteArray();
216    
217    
218          // initialize for signing
219          session.signInit(Mechanism.RSA_PKCS, selectedSignatureKey);
220    
221          // sign the data to be signed
222          byte[] signatureValue = session.sign(toBeEncrypted);
223    
224          // set the signature value in the signer info
225          signerInfo.setEncryptedDigest(signatureValue);
226    
227          // and add the signer info object to the PKCS#7 signed data object
228          signedData.addSignerInfo(signerInfo);
229    
230          output_.println("Writing signature to file: " + args[2]);
231    
232          OutputStream signatureOutput = new FileOutputStream(args[2]);
233          signedData.writeTo(signatureOutput);
234          signatureOutput.flush();
235          signatureOutput.close();
236    
237          output_.println("################################################################################");
238    
239          session.closeSession();
240          pkcs11Module.finalize(null);
241    
242        } catch (Throwable thr) {
243          thr.printStackTrace();
244        } finally {
245          output_.close();
246        }
247      }
248    
249      public static void printUsage() {
250        output_.println("Usage: SignPKCS7 <PKCS#11 module> <file to be signed> <PKCS#7 signed data file>");
251        output_.println(" e.g.: SignPKCS7 pk2priv.dll data.dat signedData.p7");
252        output_.println("The given DLL must be in the search path of the system.");
253      }
254    
255    }