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