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.FileOutputStream;
048    import java.io.InputStreamReader;
049    import java.io.OutputStream;
050    import java.io.PrintWriter;
051    import java.math.BigInteger;
052    import java.security.Signature;
053    import java.util.Arrays;
054    import java.util.Calendar;
055    import java.util.GregorianCalendar;
056    import java.util.List;
057    
058    import iaik.asn1.ObjectID;
059    import iaik.asn1.structures.AlgorithmID;
060    import iaik.asn1.structures.Name;
061    import iaik.asn1.structures.PolicyInformation;
062    import iaik.asn1.structures.PolicyQualifierInfo;
063    import iaik.pkcs.pkcs11.Mechanism;
064    import iaik.pkcs.pkcs11.MechanismInfo;
065    import iaik.pkcs.pkcs11.Module;
066    import iaik.pkcs.pkcs11.Session;
067    import iaik.pkcs.pkcs11.Token;
068    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
069    import iaik.security.rsa.RSAPublicKey;
070    import iaik.utils.RFC2253NameParser;
071    import iaik.x509.V3Extension;
072    import iaik.x509.X509Certificate;
073    import iaik.x509.extensions.BasicConstraints;
074    import iaik.x509.extensions.CertificatePolicies;
075    import iaik.x509.extensions.KeyUsage;
076    
077    
078    
079    /**
080     * Creates a self-signed X.509 certificate using a token. The actual certificate specific
081     * operations are in the last section of this demo.
082     * The hash is calculated outside the token. This implementation just uses raw
083     * RSA.
084     *
085     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
086     * @version 0.1
087     * @invariants
088     */
089    public class SelfSignCertificate {
090    
091      static PrintWriter output_;
092    
093      static BufferedReader input_;
094    
095      static {
096        try {
097          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
098          output_ = new PrintWriter(System.out, true);
099          input_ = new BufferedReader(new InputStreamReader(System.in));
100        } catch (Throwable thr) {
101          thr.printStackTrace();
102          output_ = new PrintWriter(System.out, true);
103          input_ = new BufferedReader(new InputStreamReader(System.in));
104        }
105      }
106    
107      public static void main(String[] args) {
108        if (args.length != 3) {
109          printUsage();
110          System.exit(1);
111        }
112    
113        try {
114    
115          Module pkcs11Module = Module.getInstance(args[0]);
116          pkcs11Module.initialize(null);
117    
118          Token token = Util.selectToken(pkcs11Module, output_, input_);
119          if (token == null) {
120            output_.println("We have no token to proceed. Finished.");
121            output_.flush();
122            System.exit(0);
123          }
124    
125          List supportedMechanisms = Arrays.asList(token.getMechanismList());
126          if (!supportedMechanisms.contains(Mechanism.RSA_PKCS)) {
127            output_.print("This token does not support raw RSA signing!");
128            output_.flush();
129            System.exit(0);
130          } else {
131            MechanismInfo rsaMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS);
132            if (!rsaMechanismInfo.isSign()) {
133              output_.print("This token does not support RSA signing according to PKCS!");
134              output_.flush();
135              System.exit(0);
136            }
137          }
138    
139          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_);
140    
141          // first we search for private RSA keys that we can use for signing
142          RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();
143          privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
144    
145          KeyAndCertificate selectedSignatureKeyAndCertificate =
146              Util.selectKeyAndCertificate(session, privateSignatureKeyTemplate, output_, input_);
147          if (selectedSignatureKeyAndCertificate == null) {
148            output_.println("We have no signature key to proceed. Finished.");
149            output_.flush();
150            System.exit(0);
151          }
152    
153          RSAPrivateKey selectedSignatureKey = (RSAPrivateKey) selectedSignatureKeyAndCertificate.getKey();
154          
155          // get the public key components from the private
156          byte[] modulusBytes = selectedSignatureKey.getModulus().getByteArrayValue();
157          byte[] publicExponentBytes = selectedSignatureKey.getPublicExponent().getByteArrayValue();
158          RSAPublicKey publicKey = 
159              new RSAPublicKey(new BigInteger(1, modulusBytes), new BigInteger(1, publicExponentBytes));
160    
161          // here the interesting code starts
162    
163          output_.println("################################################################################");
164          output_.println("slef-signing demo certificate");
165    
166          Signature tokenSignatureEngine =
167              new PKCS11SignatureEngine("SHA1withRSA", session, Mechanism.RSA_PKCS, AlgorithmID.sha1);
168          AlgorithmIDAdapter pkcs11Sha1RSASignatureAlgorithmID = new AlgorithmIDAdapter(AlgorithmID.sha1WithRSAEncryption);
169          pkcs11Sha1RSASignatureAlgorithmID.setSignatureInstance(tokenSignatureEngine);
170    
171          RFC2253NameParser subjectNameParser = new RFC2253NameParser(args[1]);
172          Name subjectName = subjectNameParser.parse();
173    
174          // create a certificate
175          X509Certificate certificate = new X509Certificate();
176          
177          // set subject and issuer
178          certificate.setSubjectDN(subjectName);
179          certificate.setIssuerDN(subjectName);
180          
181          // set pulbic key
182          certificate.setPublicKey(publicKey);
183          
184          // set serial number
185          certificate.setSerialNumber(new BigInteger("1"));
186          
187          // set validity
188          Calendar date = new GregorianCalendar();
189          certificate.setValidNotBefore(date.getTime()); // valid from now
190          date.add(Calendar.YEAR, 3);
191          certificate.setValidNotAfter(date.getTime()); // for 3 years
192          
193          // set extensions
194          V3Extension basicConstraints = new BasicConstraints(true);
195          certificate.addExtension(basicConstraints);
196    
197          V3Extension keyUsage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature) ;
198          certificate.addExtension(keyUsage);
199    
200          PolicyQualifierInfo policyQualifierInfo = new PolicyQualifierInfo(null, null, "This certificate may be used for demonstration purposes only.");
201          PolicyInformation policyInformation = new PolicyInformation(new ObjectID("1.3.6.1.4.1.2706.2.2.1.1.1.1.1") , new PolicyQualifierInfo[] {policyQualifierInfo});
202          CertificatePolicies certificatePolicies = new CertificatePolicies(new PolicyInformation[] {policyInformation});
203          V3Extension policies = certificatePolicies;
204          certificate.addExtension(policies);
205    
206          java.security.PrivateKey tokenSignatureKey = new TokenPrivateKey(selectedSignatureKey);
207    
208          output_.print("signing certificate... ");
209          certificate.sign(pkcs11Sha1RSASignatureAlgorithmID , tokenSignatureKey);
210          output_.println("finished");
211    
212          output_.print("writing certificate to file \"");
213          output_.print(args[2]);
214          output_.print("\"... ");
215          OutputStream certificateStream = new FileOutputStream(args[2]);
216          certificate.writeTo(certificateStream);
217          output_.println("finished");
218    
219          output_.println("################################################################################");
220    
221          session.closeSession();
222          pkcs11Module.finalize(null);
223    
224        } catch (Throwable thr) {
225          thr.printStackTrace();
226        } finally {
227          output_.close();
228        }
229      }
230    
231      public static void printUsage() {
232        output_.println("Usage: SelfSignCertificate <PKCS#11 module> <RFC2253 subject name> <DER-encoded certificate output file>");
233        output_.println(" e.g.: SelfSignCertificate aetpkss1.dll \"CN=Karl Scheibelhofer,O=IAIK,C=AT,EMAIL=karl.scheibelhofer@iaik.at\" selfSignedCert.der");
234        output_.println("The given DLL must be in the search path of the system.");
235      }
236    
237    }