0N/A/*
2362N/A * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage sun.security.x509;
0N/A
0N/Aimport java.io.IOException;
0N/Aimport java.security.cert.X509Certificate;
0N/Aimport java.security.cert.CertificateException;
0N/Aimport java.security.cert.CertificateEncodingException;
0N/Aimport java.security.*;
0N/Aimport java.util.Date;
0N/A
0N/Aimport sun.security.pkcs.PKCS10;
0N/A
0N/A
0N/A/**
0N/A * Generate a pair of keys, and provide access to them. This class is
0N/A * provided primarily for ease of use.
0N/A *
0N/A * <P>This provides some simple certificate management functionality.
0N/A * Specifically, it allows you to create self-signed X.509 certificates
0N/A * as well as PKCS 10 based certificate signing requests.
0N/A *
0N/A * <P>Keys for some public key signature algorithms have algorithm
0N/A * parameters, such as DSS/DSA. Some sites' Certificate Authorities
0N/A * adopt fixed algorithm parameters, which speeds up some operations
0N/A * including key generation and signing. <em>At this time, this interface
0N/A * does not provide a way to provide such algorithm parameters, e.g.
0N/A * by providing the CA certificate which includes those parameters.</em>
0N/A *
0N/A * <P>Also, note that at this time only signature-capable keys may be
0N/A * acquired through this interface. Diffie-Hellman keys, used for secure
0N/A * key exchange, may be supported later.
0N/A *
0N/A * @author David Brownell
0N/A * @author Hemma Prafullchandra
0N/A * @see PKCS10
0N/A * @see X509CertImpl
0N/A */
0N/Apublic final class CertAndKeyGen {
0N/A /**
0N/A * Creates a CertAndKeyGen object for a particular key type
0N/A * and signature algorithm.
0N/A *
0N/A * @param keyType type of key, e.g. "RSA", "DSA"
0N/A * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
0N/A * "MD2WithRSA", "SHAwithDSA".
0N/A * @exception NoSuchAlgorithmException on unrecognized algorithms.
0N/A */
0N/A public CertAndKeyGen (String keyType, String sigAlg)
0N/A throws NoSuchAlgorithmException
0N/A {
0N/A keyGen = KeyPairGenerator.getInstance(keyType);
0N/A this.sigAlg = sigAlg;
0N/A }
0N/A
0N/A /**
0N/A * Creates a CertAndKeyGen object for a particular key type,
0N/A * signature algorithm, and provider.
0N/A *
0N/A * @param keyType type of key, e.g. "RSA", "DSA"
0N/A * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
0N/A * "MD2WithRSA", "SHAwithDSA".
0N/A * @param providerName name of the provider
0N/A * @exception NoSuchAlgorithmException on unrecognized algorithms.
0N/A * @exception NoSuchProviderException on unrecognized providers.
0N/A */
0N/A public CertAndKeyGen (String keyType, String sigAlg, String providerName)
0N/A throws NoSuchAlgorithmException, NoSuchProviderException
0N/A {
0N/A if (providerName == null) {
0N/A keyGen = KeyPairGenerator.getInstance(keyType);
0N/A } else {
0N/A try {
0N/A keyGen = KeyPairGenerator.getInstance(keyType, providerName);
0N/A } catch (Exception e) {
0N/A // try first available provider instead
0N/A keyGen = KeyPairGenerator.getInstance(keyType);
0N/A }
0N/A }
0N/A this.sigAlg = sigAlg;
0N/A }
0N/A
0N/A /**
0N/A * Sets the source of random numbers used when generating keys.
0N/A * If you do not provide one, a system default facility is used.
0N/A * You may wish to provide your own source of random numbers
0N/A * to get a reproducible sequence of keys and signatures, or
0N/A * because you may be able to take advantage of strong sources
0N/A * of randomness/entropy in your environment.
0N/A */
0N/A public void setRandom (SecureRandom generator)
0N/A {
0N/A prng = generator;
0N/A }
0N/A
0N/A // want "public void generate (X509Certificate)" ... inherit DSA/D-H param
0N/A
0N/A /**
0N/A * Generates a random public/private key pair, with a given key
0N/A * size. Different algorithms provide different degrees of security
0N/A * for the same key size, because of the "work factor" involved in
0N/A * brute force attacks. As computers become faster, it becomes
0N/A * easier to perform such attacks. Small keys are to be avoided.
0N/A *
0N/A * <P>Note that not all values of "keyBits" are valid for all
0N/A * algorithms, and not all public key algorithms are currently
0N/A * supported for use in X.509 certificates. If the algorithm
0N/A * you specified does not produce X.509 compatible keys, an
0N/A * invalid key exception is thrown.
0N/A *
0N/A * @param keyBits the number of bits in the keys.
0N/A * @exception InvalidKeyException if the environment does not
0N/A * provide X.509 public keys for this signature algorithm.
0N/A */
0N/A public void generate (int keyBits)
0N/A throws InvalidKeyException
0N/A {
0N/A KeyPair pair;
0N/A
0N/A try {
0N/A if (prng == null) {
0N/A prng = new SecureRandom();
0N/A }
0N/A keyGen.initialize(keyBits, prng);
0N/A pair = keyGen.generateKeyPair();
0N/A
0N/A } catch (Exception e) {
0N/A throw new IllegalArgumentException(e.getMessage());
0N/A }
0N/A
0N/A publicKey = pair.getPublic();
0N/A privateKey = pair.getPrivate();
5639N/A
5639N/A // publicKey's format must be X.509 otherwise
5639N/A // the whole CertGen part of this class is broken.
5639N/A if (!"X.509".equalsIgnoreCase(publicKey.getFormat())) {
5639N/A throw new IllegalArgumentException("publicKey's is not X.509, but "
5639N/A + publicKey.getFormat());
5639N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the public key of the generated key pair if it is of type
0N/A * <code>X509Key</code>, or null if the public key is of a different type.
0N/A *
0N/A * XXX Note: This behaviour is needed for backwards compatibility.
0N/A * What this method really should return is the public key of the
0N/A * generated key pair, regardless of whether or not it is an instance of
0N/A * <code>X509Key</code>. Accordingly, the return type of this method
0N/A * should be <code>PublicKey</code>.
0N/A */
0N/A public X509Key getPublicKey()
0N/A {
0N/A if (!(publicKey instanceof X509Key)) {
0N/A return null;
0N/A }
0N/A return (X509Key)publicKey;
0N/A }
0N/A
5639N/A /**
5639N/A * Always returns the public key of the generated key pair. Used
5639N/A * by KeyTool only.
5639N/A *
5639N/A * The publicKey is not necessarily to be an instance of
5639N/A * X509Key in some JCA/JCE providers, for example SunPKCS11.
5639N/A */
5639N/A public PublicKey getPublicKeyAnyway() {
5639N/A return publicKey;
5639N/A }
0N/A
0N/A /**
0N/A * Returns the private key of the generated key pair.
0N/A *
0N/A * <P><STRONG><em>Be extremely careful when handling private keys.
0N/A * When private keys are not kept secret, they lose their ability
0N/A * to securely authenticate specific entities ... that is a huge
0N/A * security risk!</em></STRONG>
0N/A */
0N/A public PrivateKey getPrivateKey ()
0N/A {
0N/A return privateKey;
0N/A }
0N/A
0N/A /**
0N/A * Returns a self-signed X.509v3 certificate for the public key.
0N/A * The certificate is immediately valid. No extensions.
0N/A *
0N/A * <P>Such certificates normally are used to identify a "Certificate
0N/A * Authority" (CA). Accordingly, they will not always be accepted by
0N/A * other parties. However, such certificates are also useful when
0N/A * you are bootstrapping your security infrastructure, or deploying
0N/A * system prototypes.
0N/A *
0N/A * @param myname X.500 name of the subject (who is also the issuer)
0N/A * @param firstDate the issue time of the certificate
0N/A * @param validity how long the certificate should be valid, in seconds
0N/A * @exception CertificateException on certificate handling errors.
0N/A * @exception InvalidKeyException on key handling errors.
0N/A * @exception SignatureException on signature handling errors.
0N/A * @exception NoSuchAlgorithmException on unrecognized algorithms.
0N/A * @exception NoSuchProviderException on unrecognized providers.
0N/A */
0N/A public X509Certificate getSelfCertificate (
0N/A X500Name myname, Date firstDate, long validity)
0N/A throws CertificateException, InvalidKeyException, SignatureException,
0N/A NoSuchAlgorithmException, NoSuchProviderException
0N/A {
5639N/A return getSelfCertificate(myname, firstDate, validity, null);
5639N/A }
5639N/A
5639N/A // Like above, plus a CertificateExtensions argument, which can be null.
5639N/A public X509Certificate getSelfCertificate (X500Name myname, Date firstDate,
5639N/A long validity, CertificateExtensions ext)
5639N/A throws CertificateException, InvalidKeyException, SignatureException,
5639N/A NoSuchAlgorithmException, NoSuchProviderException
5639N/A {
0N/A X509CertImpl cert;
0N/A Date lastDate;
0N/A
0N/A try {
0N/A lastDate = new Date ();
0N/A lastDate.setTime (firstDate.getTime () + validity * 1000);
0N/A
0N/A CertificateValidity interval =
0N/A new CertificateValidity(firstDate,lastDate);
0N/A
0N/A X509CertInfo info = new X509CertInfo();
0N/A // Add all mandatory attributes
0N/A info.set(X509CertInfo.VERSION,
0N/A new CertificateVersion(CertificateVersion.V3));
963N/A info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
963N/A new java.util.Random().nextInt() & 0x7fffffff));
1955N/A AlgorithmId algID = AlgorithmId.getAlgorithmId(sigAlg);
0N/A info.set(X509CertInfo.ALGORITHM_ID,
0N/A new CertificateAlgorithmId(algID));
0N/A info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname));
0N/A info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
0N/A info.set(X509CertInfo.VALIDITY, interval);
1955N/A info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname));
5639N/A if (ext != null) info.set(X509CertInfo.EXTENSIONS, ext);
0N/A
0N/A cert = new X509CertImpl(info);
0N/A cert.sign(privateKey, this.sigAlg);
0N/A
0N/A return (X509Certificate)cert;
0N/A
0N/A } catch (IOException e) {
0N/A throw new CertificateEncodingException("getSelfCert: " +
0N/A e.getMessage());
0N/A }
0N/A }
0N/A
0N/A // Keep the old method
0N/A public X509Certificate getSelfCertificate (X500Name myname, long validity)
0N/A throws CertificateException, InvalidKeyException, SignatureException,
0N/A NoSuchAlgorithmException, NoSuchProviderException
0N/A {
0N/A return getSelfCertificate(myname, new Date(), validity);
0N/A }
0N/A
0N/A /**
0N/A * Returns a PKCS #10 certificate request. The caller uses either
0N/A * <code>PKCS10.print</code> or <code>PKCS10.toByteArray</code>
0N/A * operations on the result, to get the request in an appropriate
0N/A * transmission format.
0N/A *
0N/A * <P>PKCS #10 certificate requests are sent, along with some proof
0N/A * of identity, to Certificate Authorities (CAs) which then issue
0N/A * X.509 public key certificates.
0N/A *
0N/A * @param myname X.500 name of the subject
0N/A * @exception InvalidKeyException on key handling errors.
0N/A * @exception SignatureException on signature handling errors.
0N/A */
0N/A public PKCS10 getCertRequest (X500Name myname)
0N/A throws InvalidKeyException, SignatureException
0N/A {
0N/A PKCS10 req = new PKCS10 (publicKey);
0N/A
0N/A try {
1955N/A Signature signature = Signature.getInstance(sigAlg);
1955N/A signature.initSign (privateKey);
1955N/A req.encodeAndSign(myname, signature);
0N/A
0N/A } catch (CertificateException e) {
0N/A throw new SignatureException (sigAlg + " CertificateException");
0N/A
0N/A } catch (IOException e) {
0N/A throw new SignatureException (sigAlg + " IOException");
0N/A
0N/A } catch (NoSuchAlgorithmException e) {
0N/A // "can't happen"
0N/A throw new SignatureException (sigAlg + " unavailable?");
0N/A }
0N/A return req;
0N/A }
0N/A
0N/A private SecureRandom prng;
0N/A private String sigAlg;
0N/A private KeyPairGenerator keyGen;
0N/A private PublicKey publicKey;
0N/A private PrivateKey privateKey;
0N/A}