Example usage for org.bouncycastle.asn1 DERSequence DERSequence

List of usage examples for org.bouncycastle.asn1 DERSequence DERSequence

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERSequence DERSequence.

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

From source file:org.kse.crypto.privatekey.OpenSslPvkUtil.java

License:Open Source License

/**
 * OpenSSL encode a private key.//  w w w .  j  av a2s  .  co  m
 *
 * @return The encoding
 * @param privateKey
 *            The private key
 * @throws CryptoException
 *             Problem encountered while getting the encoded private key
 */
public static byte[] get(PrivateKey privateKey) throws CryptoException {
    // DER encoding for each key type is a sequence
    ASN1EncodableVector vec = new ASN1EncodableVector();

    if (privateKey instanceof ECPrivateKey) {
        try {
            org.bouncycastle.asn1.sec.ECPrivateKey ecPrivateKey = org.bouncycastle.asn1.sec.ECPrivateKey
                    .getInstance(privateKey.getEncoded());
            return ecPrivateKey.toASN1Primitive().getEncoded();
        } catch (IOException e) {
            throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), e);
        }
    } else if (privateKey instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;

        vec.add(new ASN1Integer(VERSION));
        vec.add(new ASN1Integer(rsaPrivateKey.getModulus()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPublicExponent()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPrivateExponent()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPrimeP()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPrimeQ()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentP()));
        vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentQ()));
        vec.add(new ASN1Integer(rsaPrivateKey.getCrtCoefficient()));
    } else {
        DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey;
        DSAParams dsaParams = dsaPrivateKey.getParams();

        BigInteger primeModulusP = dsaParams.getP();
        BigInteger primeQ = dsaParams.getQ();
        BigInteger generatorG = dsaParams.getG();
        BigInteger secretExponentX = dsaPrivateKey.getX();

        // Derive public key from private key parts, ie Y = G^X mod P
        BigInteger publicExponentY = generatorG.modPow(secretExponentX, primeModulusP);

        vec.add(new ASN1Integer(VERSION));
        vec.add(new ASN1Integer(primeModulusP));
        vec.add(new ASN1Integer(primeQ));
        vec.add(new ASN1Integer(generatorG));
        vec.add(new ASN1Integer(publicExponentY));
        vec.add(new ASN1Integer(secretExponentX));
    }
    DERSequence derSequence = new DERSequence(vec);

    try {
        return derSequence.getEncoded();
    } catch (IOException ex) {
        throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), ex);
    }
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

protected List<Extension> createExtensions(PublicKey publicKey, X509Certificate issuerCertificate)
        throws CertIOException, NoSuchAlgorithmException, IOException {

    List<Extension> extensions = new ArrayList<>();

    String certType = getProperty(PROPERTY_CERT_TYPE, CERT_TYPE_TLS);

    // backward compatibility
    if (CERT_TYPE_CA_OLD.equals(certType)) {
        certType = CERT_TYPE_CA;/*from   w ww  .ja  v  a 2s . c  o m*/
    }

    // subject key identifier
    boolean criticalKeyIdentifier = getProperty(PROPERTY_CERT_CRITICAL_KEY_IDENTIFIER, false);
    extensions.add(new Extension(Extension.subjectKeyIdentifier, criticalKeyIdentifier,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getEncoded()));

    // basic constraints
    if (CERT_TYPE_CA.equals(certType)) {
        boolean criticalCaConstraints = getProperty(PROPERTY_CERT_CRITICAL_CA, true);
        int chainLengthConstraint = getProperty(PROPERTY_CERT_CHAIN_LENGTH, 0);
        if (chainLengthConstraint > 0) {
            extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints,
                    new BasicConstraints(chainLengthConstraint).getEncoded()));
        } else {
            extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints,
                    new BasicConstraints(true).getEncoded()));
        }
    }

    // key usage
    int keyUsageInt = getKeyUsage(certType);
    if (keyUsageInt != 0) {
        // FIXME: test whether we can default to true here
        boolean criticalKeyUsage = getProperty(PROPERTY_CERT_CRITICAL_KEY_USAGE, false);
        KeyUsage keyUsage = new KeyUsage(keyUsageInt);
        extensions.add(new Extension(Extension.keyUsage, criticalKeyUsage, keyUsage.getEncoded()));
    }

    // extended key usage
    KeyPurposeId[] keyPurposeDefault = null;
    if (CERT_TYPE_TLS.equals(certType)) {
        // defaults for TLS
        keyPurposeDefault = new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth };
    }
    boolean criticalKeyPurpose = getProperty(PROPERTY_CERT_CRITICAL_KEY_PURPOSE, false);
    KeyPurposeId[] keyPurpose = createKeyPurposeIds(keyPurposeDefault);
    if (keyPurpose != null) {
        extensions.add(new Extension(Extension.extendedKeyUsage, criticalKeyPurpose,
                new ExtendedKeyUsage(keyPurpose).getEncoded()));
    }

    // subjectAlternativeName
    List<ASN1Encodable> subjectAlternativeNames = extractAlternativeNames(PROPERTY_PREFIX_CERT_NAME);
    if (!subjectAlternativeNames.isEmpty()) {
        boolean criticalNames = getProperty(PROPERTY_CERT_CRITICAL_NAMES, false);
        DERSequence subjectAlternativeNamesExtension = new DERSequence(
                subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
        extensions.add(new Extension(Extension.subjectAlternativeName, criticalNames,
                subjectAlternativeNamesExtension.getEncoded()));
    }

    if (issuerCertificate == null) {
        // crl distribution point
        DistributionPoint[] crlDistributionPoints = createCrlDistributionPoints();
        if (crlDistributionPoints != null) {
            boolean criticalCrlDistPoints = getProperty(PROPERTY_CERT_CRITICAL_CRL_DISTRIBUTION_POINTS, false);
            extensions.add(new Extension(Extension.cRLDistributionPoints, criticalCrlDistPoints,
                    new CRLDistPoint(crlDistributionPoints).getEncoded()));
        }

        // authority information access
        AccessDescription[] accessDescriptions = createAccessDescriptions();
        if (accessDescriptions != null) {
            boolean criticalAuthorityInformationAccess = getProperty(
                    PROPERTY_CERT_CRITICAL_AUTHORITY_INFORMATION_ACCESS, false);
            extensions.add(new Extension(Extension.authorityInfoAccess, criticalAuthorityInformationAccess,
                    new AuthorityInformationAccess(accessDescriptions).getEncoded()));
        }
    } else {
        copyExtension(Extension.cRLDistributionPoints, issuerCertificate, extensions);
        copyExtension(Extension.authorityInfoAccess, issuerCertificate, extensions);
    }
    return extensions;
}

From source file:org.ndnx.ndn.impl.security.crypto.MerklePath.java

License:Open Source License

/**
 * DER-encode the path. Embed it in a DigestInfo
 * with the appropriate algorithm identifier.
 * @return the DER-encoded path/*from  ww w . ja v  a 2  s .com*/
 */
public byte[] derEncodedPath() {

    /**
     * Sequence of OCTET STRING
     */
    DERSequence sequenceOf = new DERSequence(_path);
    /**
     * Sequence of INTEGER, SEQUENCE OF OCTET STRING
     */
    DERInteger intVal = new DERInteger(leafNodeIndex());
    ASN1Encodable[] pathStruct = new ASN1Encodable[] { intVal, sequenceOf };
    DERSequence encodablePath = new DERSequence(pathStruct);
    byte[] encodedPath = encodablePath.getDEREncoded();

    // Wrap it up in a DigestInfo
    return NDNDigestHelper.digestEncoder(NDNMerkleTree.DEFAULT_MHT_ALGORITHM, encodedPath);
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * DOCUMENT ME!//from  w  w w .j  ava2 s  .  c o  m
 *
 * @param dn DOCUMENT ME!
 * @param validity DOCUMENT ME!
 * @param policyId DOCUMENT ME!
 * @param privKey DOCUMENT ME!
 * @param pubKey DOCUMENT ME!
 * @param isCA DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws NoSuchAlgorithmException DOCUMENT ME!
 * @throws SignatureException DOCUMENT ME!
 * @throws InvalidKeyException DOCUMENT ME!
 * @throws IllegalStateException
 * @throws CertificateEncodingException
 */
public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey,
        PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException,
        InvalidKeyException, CertificateEncodingException, IllegalStateException {
    // Create self signed certificate
    String sigAlg = "SHA1WithRSA";
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(pubKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA == true) {
        int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.
    try {
        if (isCA == true) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey);

    return selfcert;
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey,
        PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException {//from  w w  w . ja  va  2 s.c  o  m
    // Create self signed certificate
    String sigAlg = "SHA1WithRSA";
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(caDn));
    certgen.setPublicKey(pubKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (false) {
        //if (isCA == true) {
        int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.
    try {
        if (false) {
            //if (isCA == true) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate cert = certgen.generate(caPrivateKey);

    return cert;
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * //from  w  w w  .  jav a 2 s  .  co m
 * @param commonName - Common Name (CN) for generated certificate
 * @param organisation - Organisation (O) for generated certificate
 * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null
 * @param validityTime - the time that the certificate is valid (in days)
 * @return
 * @throws IOException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws CertificateParsingException
 */
public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate(
        String commonName, String organisation, String applicationUri, int validityTime) throws IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException,
        IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException {
    if (applicationUri == null)
        throw new NullPointerException("applicationUri must not be null");
    //Add provider for generator
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    //Initializes generator 
    SecureRandom srForCert = new SecureRandom();
    RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator();

    //Used for generating prime
    Random r = new Random(System.currentTimeMillis());
    int random = -1;

    while (random < 3) {
        random = r.nextInt(32);
    }
    //calculate(generate) possible value for public modulus
    //used method is "monte carlo -algorithm", so we calculate it as long as it generates value.
    BigInteger value = null;
    while (value == null) {
        value = BigInteger.probablePrime(random, new SecureRandom());
    }

    //Generate (Java) keypair
    genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80));
    AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair();

    //Extract the keys from parameters
    logger.debug("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic();
    RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(),
            clientPublicKey.getExponent());
    logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent="
            + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus());

    // JCE format needed for the certificate - because getEncoded() is necessary...
    PublicKey certPubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent()));
    // and this one for the KeyStore
    PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate(
            new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(),
                    clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(),
                    clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv()));

    //The data for the certificate..
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.add(Calendar.DAY_OF_YEAR, validityTime);

    X509Name certificateX509Name = new X509Name(
            "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country"));

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    certGen.setSerialNumber(serial);
    //Issuer and subject must be the same (because this is self signed)
    certGen.setIssuerDN(certificateX509Name);
    certGen.setSubjectDN(certificateX509Name);

    //expiry & start time for this certificate
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks)
    certGen.setNotAfter(expiryTime.getTime());

    certGen.setPublicKey(certPubKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //******* X.509 V3 Extensions *****************

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject());
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki);

    /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
    new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey)));
        */
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
    certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation
                            | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    BasicConstraints b = new BasicConstraints(false);

    Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage(
                    extendedKeyUsages));

    // create the extension value
    ASN1EncodableVector names = new ASN1EncodableVector();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    //      GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri);
    //      names.add(dnsName);
    final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

    // AuthorityKeyIdentifier

    final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name));
    AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
    //***** generate certificate ***********/
    X509Certificate cert = certGen.generate(certPrivKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert certificate = new Cert(cert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) certPrivKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey);
}

From source file:org.openconcerto.modules.finance.payment.ebics.crypto.X509CertificateGenerator.java

License:Open Source License

/**
 * This method implements the public one, but offers an additional parameter which is only used
 * when creating a new CA, namely the export alias to use.
 * /*  ww  w . ja v a  2 s  . c om*/
 * @param commonName @see #createCertificate(String, int, String, String)
 * @param validityDays @see #createCertificate(String, int, String, String)
 * @param exportFile @see #createCertificate(String, int, String, String)
 * @param exportPassword @see #createCertificate(String, int, String, String)
 * @param exportAlias If this additional parameter is null, a default value will be used as the
 *        "friendly name" in the PKCS12 file.
 * @return @see #createCertificate(String, int, String, String)
 * 
 * @see #X509CertificateGenerator(boolean)
 */
protected boolean createCertificate(String commonName, int validityDays, String exportFile,
        String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException,
        SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException,
        CertificateException, InvalidKeySpecException {
    if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) {
        throw new IllegalArgumentException("Can not work with null parameter");
    }

    System.out.println("Generating certificate for distinguished common subject name '" + commonName
            + "', valid for " + validityDays + " days");
    SecureRandom sr = new SecureRandom();

    // the JCE representation
    PublicKey pubKey;
    PrivateKey privKey;

    // the BCAPI representation
    RSAPrivateCrtKeyParameters privateKey = null;

    System.out.println("Creating RSA keypair");
    // generate the keypair for the new certificate

    RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
    // TODO: what are these values??
    gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80));
    AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
    System.out
            .println("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
    privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent());
    System.out.println("New public key is '" + new String(Hex.encode(pkStruct.getEncoded())) + ", exponent="
            + publicKey.getExponent() + ", modulus=" + publicKey.getModulus());
    // TODO: these two lines should go away
    // JCE format needed for the certificate - because getEncoded() is necessary...
    pubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
    // and this one for the KeyStore
    privKey = KeyFactory.getInstance("RSA")
            .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                    privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(),
                    privateKey.getDQ(), privateKey.getQInv()));

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    X500Name x509Name = new X500Name("CN=" + commonName);

    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
    if (caCert != null) {
        // Attention: this is a catch! Just using
        // "new X509Name(caCert.getSubjectDN().getName())" will not work!
        // I don't know why, because the issuerDN strings look similar with both versions.
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
    } else {
        // aha, no CA set, which means that we should create a self-signed certificate (called
        // from createCA)
        certGen.setIssuer(x509Name);
    }
    certGen.setSubject(x509Name);

    // TODO GM:
    DERObjectIdentifier sigOID = PKCSObjectIdentifiers.sha1WithRSAEncryption;// DERObjectIdentifier.
                                                                             // X509Util.getAlgorithmOID(CertificateSignatureAlgorithm);
    AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
    certGen.setSignature(sigAlgId);
    // certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId,
    // pkStruct.toASN1Object()));
    // TODO: why does the coding above not work? - make me work without PublicKey class
    certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject()));
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
    certGen.setEndDate(new Time(expiry.getTime()));

    // These X509v3 extensions are not strictly necessary, but be nice and provide them...
    Hashtable extensions = new Hashtable();
    Vector extOrdering = new Vector();
    addExtensionHelper(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey),
            extOrdering, extensions);
    if (caCert != null) {
        // again: only if we have set CA
        addExtensionHelper(X509Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions);
    } else {
        // but if we create a new self-signed cert, set its capability to be a CA
        // this is a critical extension (true)!
        addExtensionHelper(X509Extension.basicConstraints, true, new BasicConstraints(0), extOrdering,
                extensions);
    }
    certGen.setExtensions(new X509Extensions(extOrdering, extensions));

    System.out.println("Certificate structure generated, creating SHA1 digest");
    // attention: hard coded to be SHA1+RSA!
    SHA1Digest digester = new SHA1Digest();
    AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
    TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(tbsCert);

    // and now sign
    byte[] signature;

    byte[] certBlock = bOut.toByteArray();
    // first create digest
    System.out.println("Block to sign is '" + new String(Hex.encode(certBlock)) + "'");
    digester.update(certBlock, 0, certBlock.length);
    byte[] hash = new byte[digester.getDigestSize()];
    digester.doFinal(hash, 0);
    // and sign that
    if (caCert != null) {
        rsa.init(true, caPrivateKey);
    } else {
        // no CA - self sign
        System.out.println("No CA has been set, creating self-signed certificate as a new CA");
        rsa.init(true, privateKey);
    }
    DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
    byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
    signature = rsa.processBlock(digest, 0, digest.length);

    System.out.println("SHA1/RSA signature of digest is '" + new String(Hex.encode(signature)) + "'");

    // and finally construct the certificate structure
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));

    X509CertificateObject clientCert = new X509CertificateObject(
            new X509CertificateStructure(new DERSequence(v)));
    System.out.println("Verifying certificate for correct signature with CA public key");
    /*
     * if (caCert != null) { clientCert.verify(caCert.getPublicKey()); } else {
     * clientCert.verify(pubKey); }
     */

    // and export as PKCS12 formatted file along with the private key and the CA certificate
    System.out.println("Exporting certificate in PKCS12 format");

    PKCS12BagAttributeCarrier bagCert = clientCert;
    // if exportAlias is set, use that, otherwise a default name
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias));
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(pubKey));

    // this does not work as in the example
    /*
     * PKCS12BagAttributeCarrier bagKey = (PKCS12BagAttributeCarrier)privKey;
     * bagKey.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new
     * SubjectKeyIdentifierStructure(tmpKey));
     */

    JDKPKCS12KeyStore store;

    store = new JDKPKCS12KeyStore.BCPKCS12KeyStore();
    store.engineLoad(null, null);

    FileOutputStream fOut = new FileOutputStream(exportFile);
    X509Certificate[] chain;

    if (caCert != null) {
        chain = new X509Certificate[2];
        // first the client, then the CA certificate - this is the expected order for a
        // certificate chain
        chain[0] = clientCert;
        chain[1] = caCert;
    } else {
        // for a self-signed certificate, there is no chain...
        chain = new X509Certificate[1];
        chain[0] = clientCert;
    }

    store.engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey,
            exportPassword.toCharArray(), chain);
    store.engineStore(fOut, exportPassword.toCharArray());

    return true;
}

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey pubKey, X509Name name,
        BigInteger sNumber) {/*from w ww  .j a  v a 2 s  .c o  m*/
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bIn).readObject());
        //            (ASN1Sequence)new DERInputStream(bIn).readObject()

        GeneralName genName = new GeneralName(name);
        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(genName);

        return new AuthorityKeyIdentifier(info, new GeneralNames(new DERSequence(v)), sNumber);
    } catch (Exception e) {
        throw new RuntimeException("error creating AuthorityKeyId");
    }
}