Save This Page
Home » geronimo-2.2-source-release » org.apache.geronimo.console.core.keystore » [javadoc | source]
    1   /**
    2    *  Licensed to the Apache Software Foundation (ASF) under one or more
    3    *  contributor license agreements.  See the NOTICE file distributed with
    4    *  this work for additional information regarding copyright ownership.
    5    *  The ASF licenses this file to You under the Apache License, Version 2.0
    6    *  (the "License"); you may not use this file except in compliance with
    7    *  the License.  You may obtain a copy of the License at
    8    *
    9    *     http://www.apache.org/licenses/LICENSE-2.0
   10    *
   11    *  Unless required by applicable law or agreed to in writing, software
   12    *  distributed under the License is distributed on an "AS IS" BASIS,
   13    *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    *  See the License for the specific language governing permissions and
   15    *  limitations under the License.
   16    */
   17   
   18   package org.apache.geronimo.console.core.keystore;
   19   
   20   import java.io.ByteArrayInputStream;
   21   import java.io.ByteArrayOutputStream;
   22   import java.io.File;
   23   import java.io.FileInputStream;
   24   import java.io.FileOutputStream;
   25   import java.io.IOException;
   26   import java.io.InputStream;
   27   import java.math.BigInteger;
   28   import java.security.KeyPair;
   29   import java.security.KeyPairGenerator;
   30   import java.security.KeyStore;
   31   import java.security.KeyStoreException;
   32   import java.security.NoSuchAlgorithmException;
   33   import java.security.PrivateKey;
   34   import java.security.PublicKey;
   35   import java.security.cert.Certificate;
   36   import java.security.cert.CertificateException;
   37   import java.security.cert.CertificateFactory;
   38   import java.security.cert.X509Certificate;
   39   import java.util.ArrayList;
   40   import java.util.Collection;
   41   import java.util.Date;
   42   import java.util.Enumeration;
   43   import java.util.Hashtable;
   44   import java.util.Iterator;
   45   import java.util.List;
   46   import java.util.Vector;
   47   
   48   import org.apache.geronimo.crypto.asn1.ASN1Set;
   49   import org.apache.geronimo.crypto.asn1.DEROutputStream;
   50   import org.apache.geronimo.crypto.asn1.x509.X509Name;
   51   import org.apache.geronimo.crypto.encoders.Base64;
   52   import org.apache.geronimo.crypto.jce.PKCS10CertificationRequest;
   53   import org.apache.geronimo.crypto.jce.X509Principal;
   54   import org.apache.geronimo.crypto.jce.X509V1CertificateGenerator;
   55   import org.apache.geronimo.gbean.GBeanInfo;
   56   import org.apache.geronimo.gbean.GBeanInfoBuilder;
   57   import org.apache.geronimo.gbean.GBeanLifecycle;
   58   import org.apache.geronimo.gbean.WaitingException;
   59   import org.apache.geronimo.system.serverinfo.ServerInfo;
   60   import org.slf4j.Logger;
   61   import org.slf4j.LoggerFactory;
   62   
   63   public class KeyStoreGBean implements GBeanLifecycle {
   64   
   65       private static final Logger log = LoggerFactory.getLogger(KeyStoreGBean.class);
   66   
   67       private String keyStoreType;
   68   
   69       private String keyStoreProvider;
   70   
   71       private String keyStoreLocation;
   72   
   73       private String keyStorePassword;
   74   
   75       private String keyPassword;
   76   
   77       private KeyStore keystore;
   78   
   79       // Used to resolve keystore path.
   80       private ServerInfo serverInfo;
   81   
   82       public KeyStoreGBean() {
   83       }
   84   
   85       public void doStart() throws WaitingException, Exception {
   86   
   87           //Security.addProvider(new BouncyCastleProvider());
   88   
   89           this.keystore = KeyStore.getInstance(keyStoreType);
   90   
   91           boolean keystoreExistsFlag = true;
   92           InputStream is = null;
   93   
   94           try {
   95               File keyStore = serverInfo.resolveServer(this.keyStoreLocation);
   96               log.debug("loading keystore from " + keyStore);
   97               is = new java.io.FileInputStream(keyStore);
   98               this.keystore.load(is, this.keyStorePassword.toCharArray());
   99           } catch (java.io.FileNotFoundException e) {
  100               keystoreExistsFlag = false;
  101           } finally {
  102               try {
  103                   if (is != null) {
  104                       is.close();
  105                   }
  106               } catch (Exception e) {
  107               }
  108           }
  109   
  110           if (keystoreExistsFlag == false) {
  111               keystore.load(null, keyStorePassword.toCharArray());
  112           }
  113       }
  114   
  115       public void doStop() throws WaitingException, Exception {
  116       }
  117   
  118       public void doFail() {
  119       }
  120   
  121       public void setKeyStoreType(String keyStoreType) {
  122           this.keyStoreType = keyStoreType;
  123       }
  124   
  125       public String getKeyStoreType() {
  126           return this.keyStoreType;
  127       }
  128   
  129       public void setKeyStoreProvider(String keyStoreProvider) {
  130           this.keyStoreProvider = keyStoreProvider;
  131       }
  132   
  133       public String getKeyStoreProvider() {
  134           return this.keyStoreProvider;
  135       }
  136   
  137       public void setKeyStoreLocation(String keyStoreLocation) {
  138           this.keyStoreLocation = keyStoreLocation;
  139       }
  140   
  141       public ServerInfo getServerInfo() {
  142           return serverInfo;
  143       }
  144   
  145       public void setServerInfo(ServerInfo serverInfo) {
  146           this.serverInfo = serverInfo;
  147       }
  148   
  149       public String getKeyStoreLocation() {
  150           return this.keyStoreLocation;
  151       }
  152   
  153       public void setKeyStorePassword(String keyStorePassword) {
  154           this.keyStorePassword = keyStorePassword;
  155       }
  156   
  157       public String getKeyStorePassword() {
  158           return this.keyStorePassword;
  159       }
  160   
  161       public void setKeyPassword(String keyPassword) {
  162           this.keyPassword = keyPassword;
  163       }
  164   
  165       public String getKeyPassword() {
  166           return this.keyPassword;
  167       }
  168   
  169       public int getKeyStoreSize() throws KeyStoreException {
  170           return this.keystore.size();
  171       }
  172   
  173       public KeyEntryInfo getKeyEntryInfo(String alias) throws KeyStoreException {
  174           KeyEntryInfo info = null;
  175   
  176           if (this.keystore.isCertificateEntry(alias)) {
  177               // certificate entry
  178               info = new KeyEntryInfo(alias, "trusted certificate", keystore
  179                       .getCreationDate(alias));
  180           } else if (this.keystore.isKeyEntry(alias)) {
  181               // private key entry
  182               info = new KeyEntryInfo(alias, "private key", keystore
  183                       .getCreationDate(alias));
  184           } else {
  185               throw new KeyStoreException("invalid key entry type");
  186           }
  187           return info;
  188       }
  189   
  190       public List getKeyStoreEntries() throws KeyStoreException {
  191           List list = new ArrayList();
  192   
  193           Enumeration aliases = this.keystore.aliases();
  194   
  195           while (aliases.hasMoreElements()) {
  196               String alias = (String) aliases.nextElement();
  197               list.add(getKeyEntryInfo(alias));
  198           }
  199           return list;
  200       }
  201   
  202       public Certificate[] getCertificateChain(String alias)
  203               throws KeyStoreException {
  204           Certificate[] certs = null;
  205   
  206           if (keystore.isCertificateEntry(alias)) {
  207               Certificate cert = keystore.getCertificate(alias);
  208               certs = new Certificate[1];
  209               certs[0] = cert;
  210           } else if (keystore.isKeyEntry(alias)) {
  211               certs = keystore.getCertificateChain(alias);
  212           } else if (keystore.containsAlias(alias)) {
  213               throw new KeyStoreException("Unsupported key-store-entry, alias = "
  214                       + alias);
  215           } else {
  216               throw new KeyStoreException(
  217                       "Key-store-entry alias not found, alias = " + alias);
  218           }
  219   
  220           return certs;
  221       }
  222   
  223       public String generateCSR(String alias) throws Exception {
  224   
  225           // find certificate by alias
  226           X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
  227   
  228           // find private key by alias
  229           PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());
  230   
  231           // generate csr
  232           String csr = generateCSR(cert, key);
  233           return csr;
  234       }
  235   
  236       public String generateCSR(X509Certificate cert, PrivateKey signingKey)
  237               throws Exception {
  238   
  239           String sigalg = cert.getSigAlgName();
  240           X509Name subject = new X509Name(cert.getSubjectDN().toString());
  241           PublicKey publicKey = cert.getPublicKey();
  242           ASN1Set attributes = null;
  243   
  244           PKCS10CertificationRequest csr = new PKCS10CertificationRequest(sigalg,
  245                   subject, publicKey, attributes, signingKey);
  246   
  247           if (!csr.verify()) {
  248               throw new KeyStoreException("CSR verification failed");
  249           }
  250   
  251           ByteArrayOutputStream os = new ByteArrayOutputStream();
  252           DEROutputStream deros = new DEROutputStream(os);
  253           deros.writeObject(csr.getDERObject());
  254           String b64 = new String(Base64.encode(os.toByteArray()));
  255   
  256           final String BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  257           final String END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  258           final int CERT_REQ_LINE_LENGTH = 70;
  259   
  260           StringBuffer sbuf = new StringBuffer(BEGIN_CERT_REQ).append('\n');
  261   
  262           int idx = 0;
  263           while (idx < b64.length()) {
  264   
  265               int len = (idx + CERT_REQ_LINE_LENGTH > b64.length()) ? b64
  266                       .length()
  267                       - idx : CERT_REQ_LINE_LENGTH;
  268   
  269               String chunk = b64.substring(idx, idx + len);
  270   
  271               sbuf.append(chunk).append('\n');
  272               idx += len;
  273           }
  274   
  275           sbuf.append(END_CERT_REQ);
  276           return sbuf.toString();
  277       }
  278   
  279       public void generateKeyPair(String alias, String keyalg, Integer keysize,
  280               String sigalg, Integer validity, String cn, String ou, String o,
  281               String l, String st, String c)
  282               throws java.security.NoSuchAlgorithmException,
  283               java.security.KeyStoreException, java.security.SignatureException,
  284               java.security.InvalidKeyException,
  285               java.security.cert.CertificateException, java.io.IOException {
  286   
  287           KeyPairGenerator kpgen = KeyPairGenerator.getInstance(keyalg);
  288   
  289           kpgen.initialize(keysize.intValue());
  290   
  291           KeyPair keyPair = kpgen.generateKeyPair();
  292   
  293           X509Certificate cert = generateCert(keyPair.getPublic(), keyPair
  294                   .getPrivate(), sigalg, validity.intValue(), cn, ou, o, l, st, c);
  295   
  296           keystore.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert });
  297   
  298           saveKeyStore();
  299       }
  300   
  301       public void saveKeyStore() throws java.io.IOException,
  302               java.security.KeyStoreException,
  303               java.security.cert.CertificateException,
  304               java.security.NoSuchAlgorithmException {
  305   
  306           FileOutputStream os = null;
  307   
  308           try {
  309               File keyStore = serverInfo.resolveServer(this.keyStoreLocation);
  310               os = new FileOutputStream(keyStore);
  311   
  312               keystore.store(os, keyStorePassword.toCharArray());
  313           } finally {
  314               if (os != null) {
  315                   try {
  316                       os.close();
  317                   } catch (Exception ex) {
  318                   }
  319               }
  320           }
  321       }
  322   
  323       public X509Certificate generateCert(PublicKey publicKey,
  324               PrivateKey privateKey, String sigalg, int validity, String cn,
  325               String ou, String o, String l, String st, String c)
  326               throws java.security.SignatureException,
  327               java.security.InvalidKeyException {
  328           X509V1CertificateGenerator certgen = new X509V1CertificateGenerator();
  329   
  330           // issuer dn
  331           Vector order = new Vector();
  332           Hashtable attrmap = new Hashtable();
  333   
  334           if (cn != null) {
  335               attrmap.put(X509Principal.CN, cn);
  336               order.add(X509Principal.CN);
  337           }
  338   
  339           if (ou != null) {
  340               attrmap.put(X509Principal.OU, ou);
  341               order.add(X509Principal.OU);
  342           }
  343   
  344           if (o != null) {
  345               attrmap.put(X509Principal.O, o);
  346               order.add(X509Principal.O);
  347           }
  348   
  349           if (l != null) {
  350               attrmap.put(X509Principal.L, l);
  351               order.add(X509Principal.L);
  352           }
  353   
  354           if (st != null) {
  355               attrmap.put(X509Principal.ST, st);
  356               order.add(X509Principal.ST);
  357           }
  358   
  359           if (c != null) {
  360               attrmap.put(X509Principal.C, c);
  361               order.add(X509Principal.C);
  362           }
  363   
  364           X509Principal issuerDN = new X509Principal(order, attrmap);
  365           certgen.setIssuerDN(issuerDN);
  366   
  367           // validity
  368           long curr = System.currentTimeMillis();
  369           long untill = curr + (long) validity * 24 * 60 * 60 * 1000;
  370   
  371           certgen.setNotBefore(new Date(curr));
  372           certgen.setNotAfter(new Date(untill));
  373   
  374           // subject dn
  375           certgen.setSubjectDN(issuerDN);
  376   
  377           // public key
  378           certgen.setPublicKey(publicKey);
  379   
  380           // signature alg
  381           certgen.setSignatureAlgorithm(sigalg);
  382   
  383           // serial number
  384           certgen.setSerialNumber(new BigInteger(String.valueOf(curr)));
  385   
  386           // make certificate
  387           X509Certificate cert = certgen.generateX509Certificate(privateKey);
  388           return cert;
  389       }
  390   
  391       public void importTrustedX509Certificate(String alias, String certfile)
  392               throws java.io.FileNotFoundException,
  393               java.security.cert.CertificateException,
  394               java.security.KeyStoreException, java.io.IOException,
  395               java.security.NoSuchAlgorithmException,
  396               java.security.NoSuchProviderException {
  397           InputStream is = null;
  398   
  399           try {
  400               if (keyStoreProvider.equalsIgnoreCase("Default"))
  401               {
  402                   keyStoreProvider = new String(System.getProperty("java.security.Provider"));
  403               }
  404               CertificateFactory cf = CertificateFactory.getInstance("X.509", keyStoreProvider);
  405   
  406               is = new FileInputStream(certfile);
  407               Certificate cert = cf.generateCertificate(is);
  408   
  409               if(alias == null || alias.equals("")) {
  410                   // Generate an alias for this certificate
  411                   X509Certificate xcert = (X509Certificate)cert;
  412                   alias = xcert.getIssuerDN().toString()+":"+xcert.getSerialNumber();
  413               }
  414   
  415               keystore.setCertificateEntry(alias, cert);
  416   
  417               saveKeyStore();
  418           } finally {
  419               if (is != null) {
  420                   try {
  421                       is.close();
  422                   } catch (Exception e) {
  423                   }
  424               }
  425           }
  426       }
  427   
  428       public void importPKCS7Certificate(String alias, String certbuf)
  429               throws java.security.cert.CertificateException,
  430               java.security.NoSuchProviderException,
  431               java.security.KeyStoreException,
  432               java.security.NoSuchAlgorithmException,
  433               java.security.UnrecoverableKeyException, java.io.IOException {
  434   
  435           InputStream is = null;
  436   
  437           try {
  438               is = new ByteArrayInputStream(certbuf.getBytes());
  439               importPKCS7Certificate(alias, is);
  440           } finally {
  441               if (is != null) {
  442                   try {
  443                       is.close();
  444                   } catch (Exception e) {
  445                   }
  446               }
  447           }
  448       }
  449   
  450       public void importPKCS7Certificate(String alias, InputStream is)
  451               throws java.security.cert.CertificateException,
  452               java.security.NoSuchProviderException,
  453               java.security.KeyStoreException,
  454               java.security.NoSuchAlgorithmException,
  455               java.security.UnrecoverableKeyException, java.io.IOException {
  456   
  457           if (keyStoreProvider.equalsIgnoreCase("Default"))
  458           {
  459               keyStoreProvider = new String(System.getProperty("java.security.Provider"));
  460           }
  461           CertificateFactory cf = CertificateFactory.getInstance("X.509",keyStoreProvider);
  462           Collection certcoll = cf.generateCertificates(is);
  463   
  464           Certificate[] chain = new Certificate[certcoll.size()];
  465   
  466           Iterator iter = certcoll.iterator();
  467           for (int i = 0; iter.hasNext(); i++) {
  468               chain[i] = (Certificate) iter.next();
  469           }
  470   
  471           char[] password = keyPassword.toCharArray();
  472           keystore.setKeyEntry(alias, keystore.getKey(alias, password), password,
  473                   chain);
  474   
  475           saveKeyStore();
  476       }
  477   
  478       public void deleteEntry(String alias)
  479               throws KeyStoreException,
  480               CertificateException,
  481               NoSuchAlgorithmException, IOException {
  482   
  483           keystore.deleteEntry(alias);
  484   
  485           saveKeyStore();
  486       }
  487   
  488   
  489       public static final GBeanInfo GBEAN_INFO;
  490   
  491       static {
  492           GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(KeyStoreGBean.class);
  493   
  494           infoFactory.addAttribute("keyStoreType", String.class, true);
  495           infoFactory.addAttribute("keyStoreProvider", String.class, true);
  496           infoFactory.addAttribute("keyStoreLocation", String.class, true);
  497           infoFactory.addAttribute("keyStorePassword", String.class, true);
  498           infoFactory.addAttribute("keyPassword", String.class, true);
  499   
  500           infoFactory.addReference("serverInfo", ServerInfo.class, GBeanInfoBuilder.DEFAULT_J2EE_TYPE);
  501   
  502           infoFactory.addOperation("getKeyEntryInfo",
  503                   new Class[] { String.class });
  504           infoFactory.addOperation("getKeyStoreSize");
  505           infoFactory.addOperation("getKeyStoreEntries");
  506           infoFactory.addOperation("getCertificateChain",
  507                   new Class[] { String.class });
  508           infoFactory.addOperation("generateCSR", new Class[] { String.class });
  509   
  510           infoFactory.addOperation("generateKeyPair", new Class[] { String.class,
  511                   String.class, Integer.class, String.class, Integer.class,
  512                   String.class, String.class, String.class, String.class,
  513                   String.class, String.class });
  514   
  515           infoFactory.addOperation("importTrustedX509Certificate", new Class[] {
  516                   String.class, String.class });
  517           infoFactory.addOperation("importPKCS7Certificate", new Class[] {
  518                   String.class, String.class });
  519           infoFactory.addOperation("deleteEntry", new Class[] {String.class });
  520   
  521           GBEAN_INFO = infoFactory.getBeanInfo();
  522       }
  523   
  524       public static GBeanInfo getGBeanInfo() {
  525           return GBEAN_INFO;
  526       }
  527   
  528   }

Save This Page
Home » geronimo-2.2-source-release » org.apache.geronimo.console.core.keystore » [javadoc | source]