001: /*
002: * CreateSelfSignedCertificate.java
003: *
004: */
005:
006: /**
007: *
008: * @author ss133690
009: * @version
010: */package com.sun.portal.cli.cert;
011:
012: import java.util.*;
013: import com.sun.portal.log.common.PortalLogger;
014: import org.mozilla.jss.crypto.*;
015: import org.mozilla.jss.crypto.KeyPairGenerator;
016: import org.mozilla.jss.crypto.X509Certificate;
017: import org.mozilla.jss.util.*;
018: import org.mozilla.jss.ssl.*;
019: import org.mozilla.jss.*;
020: import org.mozilla.jss.pkcs11.*;
021: import java.security.cert.*;
022: import java.security.interfaces.*;
023: import java.security.*;
024: import java.security.PrivateKey;
025: import org.mozilla.jss.pkix.primitive.*;
026: import org.mozilla.jss.pkix.cert.*;
027: import org.mozilla.jss.pkix.cert.Certificate;
028: import org.mozilla.jss.asn1.*;
029: import org.mozilla.jss.pkcs7.*;
030:
031: public class CreateSelfSignedCertificate implements Command {
032: private JSSContext cntx;
033:
034: public boolean execute(JSSContext cntx) {
035: this .cntx = cntx;
036: CertAdminUtil.println(CertAdminConstants.newline);
037: String tmpfqdn = cntx.getHost();
038: CertAdminUtil.println(CertAdminHelpText.getDNHelpText());
039: //String fqdn = CertAdminUtil.question("What is the fully-qualified DNS name of this host? ["+tmpfqdn+"]");
040: String fqdn = CertAdminUtil.question(CertAdminLocale
041: .getPFString("q2", CertAdminConstants.q2)
042: + tmpfqdn
043: + CertAdminLocale.getPFString("q1",
044: CertAdminConstants.q1));
045: if (fqdn.equals("")) {
046: fqdn = tmpfqdn;
047: }
048: //String o = CertAdminUtil.question("What is the name of your organization (ex: Company)? []");
049: String o = CertAdminUtil.question(CertAdminLocale.getPFString(
050: "q3", CertAdminConstants.q3)
051: + CertAdminLocale.getPFString("q1",
052: CertAdminConstants.q1));
053: //String ou = CertAdminUtil.question("What is the name of your organizational unit (ex: division)? []");
054: String ou = CertAdminUtil.question(CertAdminLocale.getPFString(
055: "q4", CertAdminConstants.q4)
056: + CertAdminLocale.getPFString("q1",
057: CertAdminConstants.q1));
058: //String l = CertAdminUtil.question("What is the name of your City or Locality? []");
059: String l = CertAdminUtil.question(CertAdminLocale.getPFString(
060: "q5", CertAdminConstants.q5)
061: + CertAdminLocale.getPFString("q1",
062: CertAdminConstants.q1));
063: //String s = CertAdminUtil.question("What is the name (no abbreviation please) of your State or Province? []");
064: String s = CertAdminUtil.question(CertAdminLocale.getPFString(
065: "q6", CertAdminConstants.q6)
066: + CertAdminLocale.getPFString("q1",
067: CertAdminConstants.q1));
068: //String c = CertAdminUtil.question("What is the two-letter country code for this unit? []");
069: String c = CertAdminUtil.question(CertAdminLocale.getPFString(
070: "q7", CertAdminConstants.q7));
071: while (c.trim().length() != 2) {
072: //println("Enter a valid country code");
073: CertAdminUtil.println(CertAdminLocale.getPFString("m9",
074: CertAdminConstants.m9));
075: //c = CertAdminUtil.question("What is the two-letter country code for this unit? []");
076: c = CertAdminUtil.question(CertAdminLocale.getPFString(
077: "q7", CertAdminConstants.q7));
078: }
079: CertAdminUtil.println(CertAdminHelpText.getTokenHelpText());
080: //String token = CertAdminUtil.question("Please enter the token name []");
081: String token = CertAdminUtil.question(CertAdminLocale
082: .getPFString("q8", CertAdminConstants.q8));
083: String tmpnick = "server-cert";
084: //String nick = CertAdminUtil.question("Enter the name you like for this certificate ["+tmpnick+"]");
085: String nick = CertAdminUtil.question(CertAdminLocale
086: .getPFString("q9", CertAdminConstants.q9)
087: + tmpnick
088: + CertAdminLocale.getPFString("q1",
089: CertAdminConstants.q1));
090: if (nick.equals("")) {
091: nick = tmpnick;
092: }
093: if (JSSUtil.certExist(cntx, nick)) {
094: //println("Certificate with the specified nickname already exist!");
095: CertAdminUtil.println(CertAdminLocale.getPFString("m10",
096: CertAdminConstants.m10));
097: return false;
098: }
099: int val, tmpval = 6;
100: //String validity = CertAdminUtil.question("Enter the validity period for the certificate (months) ["+tmpval+"]");
101: String validity = CertAdminUtil.question(CertAdminLocale
102: .getPFString("q10", CertAdminConstants.q10)
103: + tmpval
104: + CertAdminLocale.getPFString("q1",
105: CertAdminConstants.q1));
106: if (validity.trim().equals("")) {
107: val = tmpval;
108: }
109: try {
110: val = new Integer(validity).intValue();
111: } catch (Exception ex) {
112: val = tmpval;
113: }
114: try {
115: //Construct the certificate DN
116: Name issuer = new Name();
117: if (!fqdn.equals(""))
118: issuer.addCommonName(fqdn);
119: if (!l.equals(""))
120: issuer.addLocalityName(l);
121: if (!s.equals(""))
122: issuer.addStateOrProvinceName(s);
123: issuer.addCountryName(c);
124: if (!o.equals(""))
125: issuer.addOrganizationName(o);
126: if (!ou.equals(""))
127: issuer.addOrganizationalUnitName(ou);
128: //Generate the secure random
129: SecureRandom rng = SecureRandom.getInstance("pkcs11prng",
130: "Mozilla-JSS");
131: int rand = nextRandInt(rng);
132:
133: String passphrase = cntx.getPasswordContext()
134: .generatePassphrase(cntx);
135: PasswordCallback password;
136: CryptoToken tok = null;
137: if (token.trim().equals("")) {
138: tok = cntx.getCryptoManager()
139: .getInternalKeyStorageToken();
140: password = new CertAdminPasswordCallback(passphrase);
141: if (!tok.passwordIsInitialized()) {
142: tok.initPassword(new NullPasswordCallback(),
143: password);
144: }
145: } else {
146: tok = cntx.getCryptoManager().getTokenByName(token);
147: password = new ConsolePasswordCallback();
148: if (!tok.passwordIsInitialized()) {
149: tok.initPassword(new NullPasswordCallback(),
150: password);
151: }
152: }
153: //Login to the crypto token.
154: tok.login(password);
155:
156: String certWithSameDN = JSSUtil.getCertWithSubject(tok,
157: issuer);
158: if (certWithSameDN != null) {
159: CertAdminUtil.println();
160: CertAdminUtil.println(CertAdminLocale.getPFString(
161: "m63", CertAdminConstants.m63));
162: CertAdminUtil.println(CertAdminLocale.getPFString(
163: "m64", CertAdminConstants.m64)
164: + CertAdminConstants.SPACE + certWithSameDN);
165: CertAdminUtil.println(CertAdminLocale.getPFString(
166: "m65", CertAdminConstants.m65)
167: + CertAdminConstants.SPACE
168: + issuer.getRFC1485());
169: CertAdminUtil.println(CertAdminLocale.getPFString(
170: "m66", CertAdminConstants.m66));
171: CertAdminUtil.question(CertAdminLocale.getPFString(
172: "m67", CertAdminConstants.m67));
173: CertAdminUtil.println(CertAdminConstants.newline);
174: return false;
175: }
176: //println("Generating self-signed certificate...");
177: CertAdminUtil.println(CertAdminLocale.getPFString("m11",
178: CertAdminConstants.m11));
179: //println("Generating key. This may take a few moments...");
180: CertAdminUtil.println(CertAdminLocale.getPFString("m12",
181: CertAdminConstants.m12));
182:
183: //Generate the key pair
184: KeyPairGenerator kpg = tok
185: .getKeyPairGenerator(KeyPairAlgorithm.RSA);
186: kpg.initialize(1024);
187: KeyPair serverPair = kpg.genKeyPair();
188: //Create the self signed cert
189: Certificate serverCert = makeCert(issuer, issuer, rand,
190: serverPair.getPrivate(), serverPair.getPublic(),
191: null, val);
192: //Import the self signed cert to the certificate database.
193: JSSUtil.verifyCertificate(serverCert);
194:
195: cntx.getCryptoManager().importCertPackage(
196: ASN1Util.encode(serverCert), nick);
197: String nickfile = cntx.getCertdir()
198: + CertAdminConstants.SEPERATOR
199: + CertAdminConstants.JSSNICKNAMEFILE;
200: if (CertAdminUtil.fileExist(nickfile)) {
201: if (!CertAdminUtil.delete(nickfile)) {
202: CertAdminUtil.println(CertAdminLocale.getPFString(
203: "m46", CertAdminConstants.m46));
204: }
205: }
206: if (!CertAdminUtil.writeLine(nick, nickfile)) {
207: CertAdminUtil.println(CertAdminLocale.getPFString(
208: "m47", CertAdminConstants.m47));
209: CertAdminUtil.println(CertAdminConstants.newline);
210: CertAdminUtil.println(CertAdminLocale.getPFString(
211: "m48", CertAdminConstants.m48));
212: }
213: } catch (Exception ex) {
214: //println("Could not generate the self signed certificate : "+ex.getMessage());
215: CertAdminUtil.println(CertAdminLocale.getPFString("m13",
216: CertAdminConstants.m13));
217: ex.printStackTrace();
218: return false;
219: }
220: //println("Generated 1024-bit RSA KeyPair!");
221: CertAdminUtil.println(CertAdminLocale.getPFString("m14",
222: CertAdminConstants.m14));
223: //println("Self-signed certificate generated.");
224: CertAdminUtil.println(CertAdminLocale.getPFString("m15",
225: CertAdminConstants.m15));
226: return true;
227:
228: }
229:
230: public boolean execute(JSSContext cntx, CertContext certcntx) {
231: this .cntx = cntx;
232: if (JSSUtil.certExist(cntx, certcntx.nick)) {
233: //println("Certificate with the specified nickname already exist!");
234: CertAdminUtil.println(CertAdminLocale.getPFString("m10",
235: CertAdminConstants.m10));
236: return false;
237: }
238:
239: try {
240: //Construct the certificate DN
241: Name issuer = new Name();
242: if (!certcntx.fqdn.equals(""))
243: issuer.addCommonName(certcntx.fqdn);
244: if (!certcntx.l.equals(""))
245: issuer.addLocalityName(certcntx.l);
246: if (!certcntx.s.equals(""))
247: issuer.addStateOrProvinceName(certcntx.s);
248: issuer.addCountryName(certcntx.c);
249: if (!certcntx.o.equals(""))
250: issuer.addOrganizationName(certcntx.o);
251: if (!certcntx.ou.equals(""))
252: issuer.addOrganizationalUnitName(certcntx.ou);
253: //Generate the secure random
254: SecureRandom rng = SecureRandom.getInstance("pkcs11prng",
255: "Mozilla-JSS");
256: int rand = nextRandInt(rng);
257:
258: String passphrase = cntx.getPasswordContext()
259: .generatePassphrase(cntx);
260: PasswordCallback password;
261: CryptoToken tok = null;
262: if (certcntx.token.trim().equals("")) {
263: tok = cntx.getCryptoManager()
264: .getInternalKeyStorageToken();
265: password = new CertAdminPasswordCallback(passphrase);
266: if (!tok.passwordIsInitialized()) {
267: tok.initPassword(new NullPasswordCallback(),
268: password);
269: }
270: } else {
271: tok = cntx.getCryptoManager().getTokenByName(
272: certcntx.token);
273: password = new ConsolePasswordCallback();
274: if (!tok.passwordIsInitialized()) {
275: tok.initPassword(new NullPasswordCallback(),
276: password);
277: }
278: }
279: //Login to the crypto token.
280: tok.login(password);
281:
282: String certWithSameDN = JSSUtil.getCertWithSubject(tok,
283: issuer);
284: if (certWithSameDN != null) {
285: CertAdminUtil.println(CertAdminLocale.getPFString(
286: "m63", CertAdminConstants.m63));
287: CertAdminUtil.println(CertAdminLocale.getPFString(
288: "m64", CertAdminConstants.m64)
289: + CertAdminConstants.SPACE + certWithSameDN);
290: CertAdminUtil.println(CertAdminLocale.getPFString(
291: "m65", CertAdminConstants.m65)
292: + CertAdminConstants.SPACE
293: + issuer.getRFC1485());
294: CertAdminUtil.println(CertAdminLocale.getPFString(
295: "m66", CertAdminConstants.m66));
296: CertAdminUtil.question(CertAdminLocale.getPFString(
297: "m67", CertAdminConstants.m67));
298: CertAdminUtil.println(CertAdminConstants.newline);
299: return false;
300: }
301:
302: //Generate the key pair
303: KeyPairGenerator kpg = tok
304: .getKeyPairGenerator(KeyPairAlgorithm.RSA);
305: kpg.initialize(1024);
306: KeyPair serverPair = kpg.genKeyPair();
307: //Create the self signed cert
308: Certificate serverCert = makeCert(issuer, issuer, rand,
309: serverPair.getPrivate(), serverPair.getPublic(),
310: null, certcntx.val);
311: //Import the self signed cert to the certificate database.
312: JSSUtil.verifyCertificate(serverCert);
313:
314: cntx.getCryptoManager().importCertPackage(
315: ASN1Util.encode(serverCert), certcntx.nick);
316: String nickfile = cntx.getCertdir()
317: + CertAdminConstants.SEPERATOR
318: + CertAdminConstants.JSSNICKNAMEFILE;
319: if (CertAdminUtil.fileExist(nickfile)) {
320: if (!CertAdminUtil.delete(nickfile)) {
321: CertAdminUtil.println(CertAdminLocale.getPFString(
322: "m46", CertAdminConstants.m46));
323: }
324: }
325: if (!CertAdminUtil.writeLine(certcntx.nick, nickfile)) {
326: CertAdminUtil.println(CertAdminLocale.getPFString(
327: "m47", CertAdminConstants.m47));
328: CertAdminUtil.println(CertAdminConstants.newline);
329: CertAdminUtil.println(CertAdminLocale.getPFString(
330: "m48", CertAdminConstants.m48));
331: }
332: } catch (Exception ex) {
333: //println("Could not generate the self signed certificate : "+ex.getMessage());
334: CertAdminUtil.println(CertAdminLocale.getPFString("m13",
335: CertAdminConstants.m13));
336: ex.printStackTrace();
337: return false;
338: }
339: //println("Generated 1024-bit RSA KeyPair!");
340: CertAdminUtil.println(CertAdminLocale.getPFString("m14",
341: CertAdminConstants.m14));
342: //println("Self-signed certificate generated.");
343: CertAdminUtil.println(CertAdminLocale.getPFString("m15",
344: CertAdminConstants.m15));
345: return true;
346:
347: }
348:
349: /**
350: * Creates a new Certificate onject.
351: */
352: protected Certificate makeCert(Name issuer, Name subject,
353: int serialNumber, PrivateKey privKey, PublicKey pubKey,
354: SEQUENCE extensions, int months) throws Exception {
355: AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(cntx
356: .getSigAlg().toOID());
357: //Set the Certificate Validity period.
358: Calendar cal = Calendar.getInstance();
359: Date notBefore = cal.getTime();
360: cal.add(Calendar.MONTH, months);
361: Date notAfter = cal.getTime();
362: //Set the certificate attributes.
363: SubjectPublicKeyInfo.Template spkiTemp = new SubjectPublicKeyInfo.Template();
364: SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) ASN1Util
365: .decode(spkiTemp, pubKey.getEncoded());
366: CertificateInfo info = new CertificateInfo(CertificateInfo.v3,
367: new INTEGER(serialNumber), sigAlgID, issuer, notBefore,
368: notAfter, subject, spki);
369: if (extensions != null) {
370: info.setExtensions(extensions);
371: }
372: return new Certificate(info, privKey, cntx.getSigAlg());
373: }
374:
375: /**
376: * Create certificate basic constraint extension.
377: */
378: protected Extension makeBasicConstraintsExtension()
379: throws Exception {
380: SEQUENCE bc = new SEQUENCE();
381: bc.addElement(new BOOLEAN(true)); // cA
382: OBJECT_IDENTIFIER bcOID = new OBJECT_IDENTIFIER(new long[] { 2,
383: 5, 29, 19 }); // from RFC 2459
384: OCTET_STRING enc = new OCTET_STRING(ASN1Util.encode(bc));
385: return new Extension(bcOID, true, enc);
386: }
387:
388: /**
389: * Generate Secure random number.
390: */
391: protected int nextRandInt(SecureRandom rand) throws Exception {
392: byte[] bytes = new byte[4];
393: rand.nextBytes(bytes);
394: return ((int) bytes[0]) << 24 | ((int) bytes[1]) << 16
395: | ((int) bytes[2]) << 8 | ((int) bytes[3]);
396: }
397:
398: }
|