    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 iaik.pkcs.pkcs11.Mechanism;
    047    import iaik.pkcs.pkcs11.MechanismInfo;
    048    import iaik.pkcs.pkcs11.Module;
    049    import iaik.pkcs.pkcs11.Session;
    050    import iaik.pkcs.pkcs11.Token;
    051    import iaik.pkcs.pkcs11.TokenInfo;
    052    import iaik.pkcs.pkcs11.objects.KeyPair;
    053    import iaik.pkcs.pkcs11.objects.Object;
    054    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
    055    import iaik.pkcs.pkcs11.objects.RSAPublicKey;
    056    import iaik.pkcs.pkcs11.wrapper.Functions;
    057    import iaik.security.provider.IAIK;
    058
    059    import java.io.BufferedReader;
    060    import java.io.FileOutputStream;
    061    import java.io.InputStreamReader;
    062    import java.io.PrintWriter;
    063    import java.math.BigInteger;
    064    import java.security.KeyFactory;
    065    import java.security.Security;
    066    import java.security.spec.RSAPublicKeySpec;
    067    import java.security.spec.X509EncodedKeySpec;
    068    import java.util.Arrays;
    069    import java.util.HashSet;
    070    import java.util.Random;
    071
    072
    073
    074    /**
    075     * This demo program generates a 1024 bit RSA key-pair on the token and writes
    076     * the public key to a file.
    077     *
    078     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
    079     * @version 0.1
    080     * @invariants
    081     */
    082    public class GenerateKeyPair {
    083
    084      static BufferedReader input_;
    085
    086      static PrintWriter output_;
    087
    088      static {
    089        try {
    090          //output_ = new PrintWriter(new FileWriter("SignAndVerify_output.txt"), true);
    091          output_ = new PrintWriter(System.out, true);
    092          input_ = new BufferedReader(new InputStreamReader(System.in));
    093        } catch (Throwable thr) {
    094          thr.printStackTrace();
    095          output_ = new PrintWriter(System.out, true);
    096          input_ = new BufferedReader(new InputStreamReader(System.in));
    097       }
    098      }
    099
    100      public static void main(String[] args) {
    101        if (args.length != 2) {
    102          printUsage();
    103          System.exit(1);
    104        }
    105
    106        try {
    107
    108          Security.addProvider(new IAIK());
    109
    110          Module pkcs11Module = Module.getInstance(args[0]);
    111          pkcs11Module.initialize(null);
    112
    113          Token token = Util.selectToken(pkcs11Module, output_, input_);
    114          TokenInfo tokenInfo = token.getTokenInfo();
    115
    116          output_.println("################################################################################");
    117          output_.println("Information of Token:");
    118          output_.println(tokenInfo);
    119          output_.println("################################################################################");
    120
    121          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RW_SESSION, output_, input_);
    122              // token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);
    123
    124          output_.println("################################################################################");
    125          output_.print("Generating new 1024 bit RSA key-pair... ");
    126          output_.flush();
    127
    128          // first check out what attributes of the keys we may set
    129          HashSet supportedMechanisms = new HashSet(Arrays.asList(token.getMechanismList()));
    130
    131          MechanismInfo signatureMechanismInfo;
    132          if (supportedMechanisms.contains(Mechanism.RSA_PKCS)) {
    133            signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS);
    134          } else if (supportedMechanisms.contains(Mechanism.RSA_X_509)) {
    135            signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_X_509);
    136          } else if (supportedMechanisms.contains(Mechanism.RSA_9796)) {
    137            signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_9796);
    138          } else if (supportedMechanisms.contains(Mechanism.RSA_PKCS_OAEP)) {
    139            signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS_OAEP);
    140          } else {
    141            signatureMechanismInfo = null;
    142          }
    143
    144          Mechanism keyPairGenerationMechanism = Mechanism.RSA_PKCS_KEY_PAIR_GEN;
    145          RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey();
    146          RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey();
    147
    148          // set the general attributes for the public key
    149          rsaPublicKeyTemplate.getModulusBits().setLongValue(new Long(1024));
    150          byte[] publicExponentBytes = {0x01, 0x00, 0x01}; // 2^16 + 1
    151          rsaPublicKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes);
    152          rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
    153          byte[] id = new byte[20];
    154          new Random().nextBytes(id);
    155          rsaPublicKeyTemplate.getId().setByteArrayValue(id);
    156          //rsaPublicKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray());
    157
    158          rsaPrivateKeyTemplate.getSensitive().setBooleanValue(Boolean.TRUE);
    159         rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
    160          rsaPrivateKeyTemplate.getPrivate().setBooleanValue(Boolean.TRUE);
    161          rsaPrivateKeyTemplate.getId().setByteArrayValue(id);
    162          //byte[] subject = args[1].getBytes();
    163          //rsaPrivateKeyTemplate.getSubject().setByteArrayValue(subject);
    164          //rsaPrivateKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray());
    165
    166          // set the attributes in a way netscape does, this should work with most tokens
    167          if (signatureMechanismInfo != null) {
    168            rsaPublicKeyTemplate.getVerify().setBooleanValue(new Boolean(signatureMechanismInfo.isVerify()));
    169            rsaPublicKeyTemplate.getVerifyRecover().setBooleanValue(new Boolean(signatureMechanismInfo.isVerifyRecover()));
    170            rsaPublicKeyTemplate.getEncrypt().setBooleanValue(new Boolean(signatureMechanismInfo.isEncrypt()));
    171            rsaPublicKeyTemplate.getDerive().setBooleanValue(new Boolean(signatureMechanismInfo.isDerive()));
    172            rsaPublicKeyTemplate.getWrap().setBooleanValue(new Boolean(signatureMechanismInfo.isWrap()));
    173
    174            rsaPrivateKeyTemplate.getSign().setBooleanValue(new Boolean(signatureMechanismInfo.isSign()));
    175            rsaPrivateKeyTemplate.getSignRecover().setBooleanValue(new Boolean(signatureMechanismInfo.isSignRecover()));
    176            rsaPrivateKeyTemplate.getDecrypt().setBooleanValue(new Boolean(signatureMechanismInfo.isDecrypt()));
    177            rsaPrivateKeyTemplate.getDerive().setBooleanValue(new Boolean(signatureMechanismInfo.isDerive()));
    178            rsaPrivateKeyTemplate.getUnwrap().setBooleanValue(new Boolean(signatureMechanismInfo.isUnwrap()));
    179          } else {
    180            // if we have no information we assume these attributes
    181            rsaPrivateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
    182            rsaPrivateKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE);
    183
    184            rsaPublicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
    185            rsaPublicKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE);
    186          }
    187
    188          // netscape does not set these attribute, so we do no either
    189          rsaPublicKeyTemplate.getKeyType().setPresent(false);
    190          rsaPublicKeyTemplate.getObjectClass().setPresent(false);
    191
    192          rsaPrivateKeyTemplate.getKeyType().setPresent(false);
    193          rsaPrivateKeyTemplate.getObjectClass().setPresent(false);
    194
    195          long time0 = System.currentTimeMillis();
    196          KeyPair generatedKeyPair = session.generateKeyPair(keyPairGenerationMechanism, rsaPublicKeyTemplate, rsaPrivateKeyTemplate);
    197          long time1 = System.currentTimeMillis();
    198
    199          RSAPublicKey generatedRSAPublicKey = (RSAPublicKey) generatedKeyPair.getPublicKey();
    200          RSAPrivateKey generatedRSAPrivateKey = (RSAPrivateKey) generatedKeyPair.getPrivateKey();
    201          // no we may work with the keys...
    202
    203          output_.println("Success [took " + (time1 - time0) + " milliseconds]");
    204          output_.println("The public key is");
    205          output_.println("_______________________________________________________________________________");
    206          output_.println(generatedRSAPublicKey);
    207          output_.println("_______________________________________________________________________________");
    208          output_.println("The private key is");
    209          output_.println("_______________________________________________________________________________");
    210          output_.println(generatedRSAPrivateKey);
    211          output_.println("_______________________________________________________________________________");
    212
    213          // write the public key to file
    214          output_.println("################################################################################");
    215          output_.println("Writing the public key of the generated key-pair to file: " + args[1]);
    216          RSAPublicKey exportableRsaPublicKey = generatedRSAPublicKey;
    217          BigInteger modulus = new BigInteger(1, exportableRsaPublicKey.getModulus().getByteArrayValue());
    218          BigInteger publicExponent = new BigInteger(1, exportableRsaPublicKey.getPublicExponent().getByteArrayValue());
    219          RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    220          KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    221          java.security.interfaces.RSAPublicKey javaRsaPublicKey = (java.security.interfaces.RSAPublicKey)
    222              keyFactory.generatePublic(rsaPublicKeySpec);
    223          X509EncodedKeySpec x509EncodedPublicKey = (X509EncodedKeySpec)
    224              keyFactory.getKeySpec(javaRsaPublicKey, X509EncodedKeySpec.class);
    225
    226          FileOutputStream publicKeyFileStream = new FileOutputStream(args[1]);
    227          publicKeyFileStream.write(x509EncodedPublicKey.getEncoded());
    228          publicKeyFileStream.flush();
    229          publicKeyFileStream.close();
    230
    231          output_.println("################################################################################");
    232
    233          // now we try to search for the generated keys
    234          output_.println("################################################################################");
    235          output_.println("Trying to search for the public key of the generated key-pair by ID: " +
    236                          Functions.toHexString(id));
    237          // set the search template for the public key
    238          RSAPublicKey exportRsaPublicKeyTemplate = new RSAPublicKey();
    239          exportRsaPublicKeyTemplate.getId().setByteArrayValue(id);
    240
    241          session.findObjectsInit(exportRsaPublicKeyTemplate);
    242          Object[] foundPublicKeys = session.findObjects(1);
    243          session.findObjectsFinal();
    244
    245          if (foundPublicKeys.length != 1) {
    246            output_.println("Error: Cannot find the public key under the given ID!");
    247          } else {
    248            output_.println("Found public key!");
    249            output_.println("_______________________________________________________________________________");
    250            output_.println(foundPublicKeys[0]);
    251            output_.println("_______________________________________________________________________________");
    252          }
    253
    254          output_.println("################################################################################");
    255
    256          session.closeSession();
    257          pkcs11Module.finalize(null);
    258
    259        } catch (Throwable thr) {
    260          thr.printStackTrace();
    261        }
    262      }
    263
    264      public static void printUsage() {
    265        output_.println("Usage: GenerateKeyPair <PKCS#11 module> <X.509 encoded public key output file>");
    266        output_.println(" e.g.: GenerateKeyPair pk2priv.dll publicKey.xpk");
    267        output_.println("The given DLL must be in the search path of the system.");
    268      }
    269
    270    }