    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.GeneralName;
    059    import iaik.pkcs.pkcs11.Mechanism;
    060    import iaik.pkcs.pkcs11.MechanismInfo;
    061    import iaik.pkcs.pkcs11.Module;
    062    import iaik.pkcs.pkcs11.Session;
    063    import iaik.pkcs.pkcs11.Token;
    064    import iaik.pkcs.pkcs11.objects.PrivateKey;
    065    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
    066    import iaik.pkcs.pkcs11.objects.X509PublicKeyCertificate;
    067    import iaik.x509.X509Certificate;
    068    import iaik.x509.ocsp.OCSPRequest;
    069    import iaik.x509.ocsp.ReqCert;
    070    import iaik.x509.ocsp.Request;
    071
    072
    073
    074    /**
    075     * Signs an OCSP request using a token. The certificate of interest is given as
    076     * argument. The signed OCSP request is written to the given output file
    077     * DER-encoded. The actual OCSP specific operations are in the last section
    078     * of this demo.
    079     * The hash is calculated outside the token. This implementation just uses raw
    080     * RSA.
    081     *
    082     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
    083     * @version 0.1
    084     * @invariants
    085     */
    086    public class SignOCSPRequest {
    087
    088      static PrintWriter output_;
    089
    090      static BufferedReader input_;
    091
    092      static {
    093        try {
    094          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
    095          output_ = new PrintWriter(System.out, true);
    096          input_ = new BufferedReader(new InputStreamReader(System.in));
    097        } catch (Throwable thr) {
    098          thr.printStackTrace();
    099          output_ = new PrintWriter(System.out, true);
    100          input_ = new BufferedReader(new InputStreamReader(System.in));
    101        }
    102      }
    103
    104      public static void main(String[] args) {
    105        if (args.length != 3) {
    106          printUsage();
    107          System.exit(1);
    108        }
    109
    110        try {
    111
    112          Module pkcs11Module = Module.getInstance(args[0]);
    113          pkcs11Module.initialize(null);
    114
    115          Token token = Util.selectToken(pkcs11Module, output_, input_);
    116          if (token == null) {
    117            output_.println("We have no token to proceed. Finished.");
    118            output_.flush();
    119            System.exit(0);
    120          }
    121
    122          List supportedMechanisms = Arrays.asList(token.getMechanismList());
    123          if (!supportedMechanisms.contains(Mechanism.RSA_PKCS)) {
    124            output_.print("This token does not support raw RSA signing!");
    125            output_.flush();
    126            System.exit(0);
    127          } else {
    128            MechanismInfo rsaMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS);
    129            if (!rsaMechanismInfo.isSign()) {
    130              output_.print("This token does not support RSA signing according to PKCS!");
    131              output_.flush();
    132              System.exit(0);
    133            }
    134          }
    135
    136          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_);
    137
    138          // first we search for private RSA keys that we can use for signing
    139          RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();
    140          privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
    141
    142          KeyAndCertificate selectedSignatureKeyAndCertificate =
    143              Util.selectKeyAndCertificate(session, privateSignatureKeyTemplate, output_, input_);
    144          if (selectedSignatureKeyAndCertificate == null) {
    145            output_.println("We have no signature key to proceed. Finished.");
    146            output_.flush();
    147            System.exit(0);
    148          }
    149
    150          PrivateKey selectedSignatureKey = (PrivateKey) selectedSignatureKeyAndCertificate.getKey();
    151          X509PublicKeyCertificate pkcs11SignerCertificate = selectedSignatureKeyAndCertificate.getCertificate();
    152          X509Certificate signerCertificate = (pkcs11SignerCertificate != null)
    153                                              ? new X509Certificate(pkcs11SignerCertificate.getValue().getByteArrayValue())
    154                                              : null;
    155
    156          // here the interesting code starts
    157
    158          output_.println("################################################################################");
    159          output_.println("creating and signing OCSP request");
    160
    161          InputStream subjectCertificateStream = new FileInputStream(args[1]);
    162          X509Certificate subjectCertificate = new X509Certificate(subjectCertificateStream);
    163
    164          ReqCert reqCert = new ReqCert(ReqCert.pKCert, subjectCertificate);
    165          Request request = new Request(reqCert);
    166          OCSPRequest ocspRequest = new OCSPRequest();
    167          ocspRequest.setRequestList(new Request[] {request});
    168
    169          if (signerCertificate != null) {
    170            // if we have the signer certificate set it in the OCSP request
    171            GeneralName requestorName =
    172                new GeneralName(GeneralName.directoryName, signerCertificate.getSubjectDN());
    173            ocspRequest.setRequestorName(requestorName);
    174            ocspRequest.setCertificates(new X509Certificate[] {signerCertificate});
    175          }
    176
    177          Signature tokenSignatureEngine =
    178              new PKCS11SignatureEngine("SHA1withRSA", session, Mechanism.RSA_PKCS, AlgorithmID.sha1);
    179          AlgorithmIDAdapter pkcs11Sha1RSASignatureAlgorithmID = new AlgorithmIDAdapter(AlgorithmID.sha1WithRSAEncryption);
    180          pkcs11Sha1RSASignatureAlgorithmID.setSignatureInstance(tokenSignatureEngine);
    181
    182          java.security.PrivateKey tokenSignatureKey = new TokenPrivateKey(selectedSignatureKey);
    183
    184          output_.print("signing OCSP request... ");
    185          ocspRequest.sign(pkcs11Sha1RSASignatureAlgorithmID, tokenSignatureKey);
    186          output_.println("finished");
    187
    188          output_.print("writing OCSP request to file \"");
    189          output_.print(args[2]);
    190          output_.print("\"... ");
    191          OutputStream certificateStream = new FileOutputStream(args[2]);
    192          ocspRequest.writeTo(certificateStream);
    193          output_.println("finished");
    194
    195          output_.println("################################################################################");
    196
    197          session.closeSession();
    198          pkcs11Module.finalize(null);
    199
    200        } catch (Throwable thr) {
    201          thr.printStackTrace();
    202        } finally {
    203          output_.close();
    204        }
    205      }
    206
    207      public static void printUsage() {
    208        output_.println("Usage: SignOCSPRequest <PKCS#11 module> <DER-encoded X.509 subject certificate> <DER-encoded OCSP request output file>");
    209        output_.println(" e.g.: SignOCSPRequest pk2priv.dll subjectCert.der signedOCSPrequest.der");
    210        output_.println("The given DLL must be in the search path of the system.");
    211      }
    212
    213    }