Java tutorial
/* * Copyright (c) 2009-2012, Martijn Brinkers, Djigzo. * * This file is part of Djigzo email encryption. * * Djigzo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3, 19 November 2007 as published by the Free Software * Foundation. * * Djigzo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Djigzo. If not, see <http://www.gnu.org/licenses/> * * Additional permission under GNU AGPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, * wsdl4j-1.6.1.jar (or modified versions of these libraries), * containing parts covered by the terms of Eclipse Public License, * tyrex license, freemarker license, dom4j license, mx4j license, * Spice Software License, Common Development and Distribution License * (CDDL), Common Public License (CPL) the licensors of this Program grant * you additional permission to convey the resulting work. */ package mitm.common.security.ca; import java.io.IOException; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import javax.security.auth.x500.X500Principal; import mitm.common.security.KeyAndCertificateImpl; import mitm.common.security.SecurityFactory; import mitm.common.security.SecurityFactoryFactory; import mitm.common.security.SecurityFactoryFactoryException; import mitm.common.security.certificate.CertificateBuilderException; import mitm.common.security.certificate.ExtendedKeyUsageType; import mitm.common.security.certificate.KeyUsageType; import mitm.common.security.certificate.SerialNumberGenerator; import mitm.common.security.certificate.X509CertificateBuilder; import mitm.common.security.certificate.impl.StandardSerialNumberGenerator; import org.apache.commons.lang.time.DateUtils; /** * CABuilder implementation that creates a CA suitable for S/MIME * * @author Martijn Brinkers * */ public class SMIMECABuilder implements CABuilder { /* * Factory used to create security object instances */ private SecurityFactory securityFactory; /* * Used for the generation of serial numbers for certificates. * * Note: SerialNumberGenerator is not thread safe */ private SerialNumberGenerator serialNumberGenerator; /* * Used by the KeyPairGenerator * * Note: SecureRandom is not thread safe */ private SecureRandom randomSource; public SMIMECABuilder() throws CAException { try { securityFactory = SecurityFactoryFactory.getSecurityFactory(); serialNumberGenerator = new StandardSerialNumberGenerator(); randomSource = securityFactory.createSecureRandom(); } catch (NoSuchAlgorithmException e) { throw new CAException(e); } catch (NoSuchProviderException e) { throw new CAException(e); } catch (SecurityFactoryFactoryException e) { throw new CAException(e); } } private KeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(keyLength, randomSource); return keyPairGenerator.generateKeyPair(); } private void checkState(CABuilderParameters parameters) throws CAException { if (parameters.getRootSubject() == null) { throw new CAException("root subject must be specified."); } if (parameters.getIntermediateSubject() == null) { throw new CAException("intermediate subject must be specified."); } if (parameters.getRootValidity() < 1) { throw new CAException("root validity must be larger than 1."); } if (parameters.getIntermediateValidity() < 1) { throw new CAException("intermediate validity must be larger than 1."); } if (parameters.getRootKeyLength() < 1024) { throw new CAException("root key length must be >= 1024."); } if (parameters.getIntermediateKeyLength() < 1024) { throw new CAException("intermediate key length must be >= 1024."); } } private X509Certificate createCertificate(PublicKey pubKey, X509Certificate issuerCertificate, PrivateKey issuerKey, X500Principal issuer, X500Principal subject, int validity, Date creationDate, int pathLengthConstraint, String signatureAlgorithm, Collection<String> crlDistributionPoints) throws CAException { try { Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.KEYCERTSIGN); keyUsage.add(KeyUsageType.CRLSIGN); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); BigInteger serialNumber = serialNumberGenerator.generate(); X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); certificateBuilder.setSubject(subject); certificateBuilder.setIssuer(issuer); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(DateUtils.addDays(creationDate, -1)); certificateBuilder.setNotAfter(DateUtils.addDays(creationDate, validity)); certificateBuilder.setPublicKey(pubKey); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm(signatureAlgorithm); certificateBuilder.setIsCA(true, true); certificateBuilder.setPathLengthConstraint(pathLengthConstraint); certificateBuilder.addSubjectKeyIdentifier(true); if (crlDistributionPoints != null && crlDistributionPoints.size() > 0) { certificateBuilder.setCRLDistributionPoints(crlDistributionPoints); } return certificateBuilder.generateCertificate(issuerKey, issuerCertificate); } catch (IOException e) { throw new CAException(e); } catch (CertificateBuilderException e) { throw new CAException(e); } } /* * Note: because SerialNumberGenerator and SecureRandom are not thread safe we will * need to synchronize. */ @Override public synchronized CABuilderResult buildCA(CABuilderParameters parameters) throws CAException { try { checkState(parameters); KeyPair rootKeyPair = generateKeyPair(parameters.getRootKeyLength()); KeyPair intermediateKeyPair = generateKeyPair(parameters.getIntermediateKeyLength()); Date creationDate = new Date(); X509Certificate root = createCertificate(rootKeyPair.getPublic(), null, rootKeyPair.getPrivate(), parameters.getRootSubject(), parameters.getRootSubject(), parameters.getRootValidity(), creationDate, 1, parameters.getSignatureAlgorithm(), null); X509Certificate intermediate = createCertificate(intermediateKeyPair.getPublic(), root, rootKeyPair.getPrivate(), parameters.getRootSubject(), parameters.getIntermediateSubject(), parameters.getIntermediateValidity(), creationDate, 0, parameters.getSignatureAlgorithm(), parameters.getCRLDistributionPoints()); return new CABuilderResultImpl(new KeyAndCertificateImpl(rootKeyPair.getPrivate(), root), new KeyAndCertificateImpl(intermediateKeyPair.getPrivate(), intermediate)); } catch (NoSuchProviderException e) { throw new CAException(e); } catch (NoSuchAlgorithmException e) { throw new CAException(e); } } }