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.FileInputStream;
048    import java.io.FileOutputStream;
049    import java.io.InputStream;
050    import java.io.InputStreamReader;
051    import java.io.OutputStream;
052    import java.io.PrintWriter;
053    import java.security.Signature;
054    import java.util.Arrays;
055    import java.util.List;
056    
057    import iaik.asn1.structures.AlgorithmID;
058    import iaik.asn1.structures.Name;
059    import iaik.pkcs.pkcs10.CertificateRequest;
060    import iaik.pkcs.pkcs11.Mechanism;
061    import iaik.pkcs.pkcs11.MechanismInfo;
062    import iaik.pkcs.pkcs11.Module;
063    import iaik.pkcs.pkcs11.Session;
064    import iaik.pkcs.pkcs11.Token;
065    import iaik.pkcs.pkcs11.objects.PrivateKey;
066    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
067    import iaik.pkcs.pkcs11.objects.X509PublicKeyCertificate;
068    import iaik.utils.PemOutputStream;
069    import iaik.utils.RFC2253NameParser;
070    import iaik.x509.X509Certificate;
071    
072    
073    
074    /**
075     * Signs a PKCS#10 certificate request using a token. The actual PKCS#10
076     * specific operations are in the last section of this demo.
077     * The hash is calculated outside the token. This implementation just uses raw
078     * RSA.
079     * This example works as follows. In general, the 
080     * <code>CertificateRequest</code> class from the IAIK JCE toolkit works with 
081     * JCA private keys only. To get it to work with the wrapper, we need a special
082     * <code>AlgorithmID</code> class (see {@link demo.pkcs.pkcs11.AlgorithmIDAdapter }) 
083     * which provides a special <code>Signature</code> engine object 
084     * (see {@link demo.pkcs.pkcs11.PKCS11SignatureEngine }) to the certificate 
085     * request object. This signature engine only accepts keys of type 
086     * {@link demo.pkcs.pkcs11.TokenPrivateKey }, which just wraps PKCS#11 key 
087     * objects. All these helper classes are required if you want to sign a 
088     * certificate request with the PKCS#11 wrapper. If you use the IAIK PKCS#11
089     * provider, everything is much easier. In this case, you do not need any
090     * of these helper classes.
091     *  
092     *
093     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
094     * @version 0.1
095     * @invariants
096     */
097    public class SignCertificateRequest {
098    
099      static PrintWriter output_;
100    
101      static BufferedReader input_;
102    
103      static {
104        try {
105          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
106          output_ = new PrintWriter(System.out, true);
107          input_ = new BufferedReader(new InputStreamReader(System.in));
108        } catch (Throwable thr) {
109          thr.printStackTrace();
110          output_ = new PrintWriter(System.out, true);
111          input_ = new BufferedReader(new InputStreamReader(System.in));
112        }
113      }
114    
115      public static void main(String[] args) {
116        if (args.length != 4) {
117          printUsage();
118          System.exit(1);
119        }
120    
121        try {
122    
123          Module pkcs11Module = Module.getInstance(args[0]);
124          pkcs11Module.initialize(null);
125    
126          Token token = Util.selectToken(pkcs11Module, output_, input_);
127          if (token == null) {
128            output_.println("We have no token to proceed. Finished.");
129            output_.flush();
130            System.exit(0);
131          }
132    
133          List supportedMechanisms = Arrays.asList(token.getMechanismList());
134          if (!supportedMechanisms.contains(Mechanism.RSA_PKCS)) {
135            output_.print("This token does not support raw RSA signing!");
136            output_.flush();
137            System.exit(0);
138          } else {
139            MechanismInfo rsaMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS);
140            if (!rsaMechanismInfo.isSign()) {
141              output_.print("This token does not support RSA signing according to PKCS!");
142              output_.flush();
143              System.exit(0);
144            }
145          }
146    
147          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_);
148    
149          // first we search for private RSA keys that we can use for signing
150          RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();
151          privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
152    
153          KeyAndCertificate selectedSignatureKeyAndCertificate =
154              Util.selectKeyAndCertificate(session, privateSignatureKeyTemplate, output_, input_);
155          if (selectedSignatureKeyAndCertificate == null) {
156            output_.println("We have no signature key to proceed. Finished.");
157            output_.flush();
158            System.exit(0);
159          }
160    
161          PrivateKey selectedSignatureKey = (PrivateKey) selectedSignatureKeyAndCertificate.getKey();
162          X509PublicKeyCertificate pkcs11SignerCertificate = selectedSignatureKeyAndCertificate.getCertificate();
163          X509Certificate signerCertificate = (pkcs11SignerCertificate != null)
164                                              ? new X509Certificate(pkcs11SignerCertificate.getValue().getByteArrayValue())
165                                              : null;
166    
167          // here the interesting code starts
168    
169          output_.println("################################################################################");
170          output_.println("generating and signing PKCS#10 certificate request");
171    
172          InputStream publicKeyInputStream = new FileInputStream(args[1]);
173          iaik.security.rsa.RSAPublicKey subjectPublicKey = new iaik.security.rsa.RSAPublicKey(publicKeyInputStream);
174    
175          RFC2253NameParser subjectNameParser = new RFC2253NameParser(args[2]);
176          Name subjectName = subjectNameParser.parse();
177    
178          CertificateRequest certificateRequest = new CertificateRequest(subjectPublicKey, subjectName);
179    
180          Signature tokenSignatureEngine =
181              new PKCS11SignatureEngine("SHA1withRSA", session, Mechanism.RSA_PKCS, AlgorithmID.sha1);
182          AlgorithmIDAdapter pkcs11Sha1RSASignatureAlgorithmID = new AlgorithmIDAdapter(AlgorithmID.sha1WithRSAEncryption);
183          pkcs11Sha1RSASignatureAlgorithmID.setSignatureInstance(tokenSignatureEngine);
184    
185          java.security.PrivateKey tokenSignatureKey = new TokenPrivateKey(selectedSignatureKey);
186    
187          output_.print("signing certificate request... ");
188          certificateRequest.sign(pkcs11Sha1RSASignatureAlgorithmID , tokenSignatureKey);
189          output_.println("finished");
190    
191          output_.print("writing certificate request to file \"");
192          output_.print(args[3]);
193          output_.print("\"... ");
194          String firstLine = "-----BEGIN NEW CERTIFICATE REQUEST-----";
195          String lastLine =  "-----END NEW CERTIFICATE REQUEST-----";
196          OutputStream certificateStream = new PemOutputStream(new FileOutputStream(args[3]), firstLine, lastLine);
197          certificateRequest.writeTo(certificateStream);
198          certificateStream.flush();
199          certificateStream.close();
200          output_.println("finished");
201    
202          output_.println("################################################################################");
203    
204          session.closeSession();
205          pkcs11Module.finalize(null);
206    
207        } catch (Throwable thr) {
208          thr.printStackTrace();
209        } finally {
210          output_.close();
211        }
212      }
213    
214      public static void printUsage() {
215        output_.println("Usage: SignCertificateRequest <PKCS#11 module> <DER-encoded X.509 public RSA key file> <RFC2253 subject name> <PEM-encoded PKCS#10 certificate request output file>");
216        output_.println(" e.g.: SignCertificateRequest pk2priv.dll publicKey.xpk \"CN=Karl Scheibelhofer,O=IAIK,C=AT,EMAIL=karl.scheibelhofer@iaik.at\" certificateRequest.p10");
217        output_.println("The given DLL must be in the search path of the system.");
218      }
219    
220    }