Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

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

Prototype

public X500Name(String dirName) 

Source Link

Usage

From source file:org.signserver.test.utils.builders.ocsp.OCSPResponseBuilder.java

License:Open Source License

private BasicOCSPResp buildBasicOCSPResp() throws OCSPResponseBuilderException {
    try {/*  ww w.ja v  a 2s . c om*/
        BasicOCSPRespBuilder gen = new BasicOCSPRespBuilder(new RespID(new X500Name(getResponderName())));

        if (getNonce() != null) {
            extensions.add(
                    new OcspExt(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
        }

        Extension[] extArray = new Extension[extensions.size()];
        int i = 0;
        for (OcspExt ext : extensions) {
            extArray[i++] = new Extension(ext.getOid(), ext.isIsCritical(), ext.getValue());
        }
        if (extArray.length > 0) {
            gen.setResponseExtensions(new Extensions(extArray));
        }

        for (OcspRespObject r : responses) {
            gen.addResponse(r.getCertId(), r.getCertStatus(), r.getThisUpdate(), r.getNextUpdate(),
                    r.getExtensions());
        }

        ContentSigner contentSigner = /*new BufferingContentSigner(*/new JcaContentSignerBuilder(
                getSignatureAlgorithm()).setProvider("BC").build(getIssuerPrivateKey());//, 20480);

        BasicOCSPResp response = gen.build(contentSigner, getChain(), getProducedAt());
        return response;
    } catch (OCSPException ex) {
        throw new OCSPResponseBuilderException(ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new OCSPResponseBuilderException(ex);
    } catch (NoSuchProviderException ex) {
        throw new OCSPResponseBuilderException(ex);
    } catch (OperatorCreationException ex) {
        throw new OCSPResponseBuilderException(ex);
    }
}

From source file:org.tastefuljava.minica.MainFrame.java

License:Open Source License

private static String formatDN(String dn) {
    dn = new X500Name(dn).toString();
    StringBuilder buf = new StringBuilder();
    int st = 0;/* ww  w .j  a  va 2s  .  co  m*/
    for (int ix = dn.indexOf(','); ix >= 0; ix = dn.indexOf(',', st)) {
        buf.append(dn.substring(st, ix + 1).trim());
        buf.append('\n');
        st = ix + 1;
    }
    buf.append(dn.substring(st).trim());
    return buf.toString();
}

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates.
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate
 * CA certificate//from   w  ww. j  ava 2  s  .  c o  m
 * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification
 * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path
 * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.)
 * @return an intermediate CA certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateIntermediateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";

    //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName());
    final X500Name issuer = new X500Name(
            StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName()));
    final UUID intermediateUUID = UUID.randomUUID();
    // provide items to X500Principal in reverse order
    final X500Principal x500Principal = new X500Principal(
            "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org");
    final X500Name subject = new X500Name(x500Principal.getName());
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(myPublicKey.getEncoded()));
    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            subject, publicKeyInfo);

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(pathLengthConstraint)); // is a CA certificate with specified certification path length

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
            // certificates
            KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                   // information
                    KeyUsage.cRLSign);

    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }

    return x509Certificate;
}

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication
 * and for message signing.//from w w  w.  j  a va2s .  c  o  m
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate
 * @param uid the subject UID
 * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime
 * @return a signed end-use certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid,
        final String domainComponent)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";
    assert uid != null : "uid must not be null";

    final String x500PrincipalString;
    // provide items to X500Principal in reverse order
    if (domainComponent == null || domainComponent.isEmpty()) {
        x500PrincipalString = "UID=" + uid + ", CN=texai.org";
    } else {
        x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org";
    }
    final X500Principal x500Principal = new X500Principal(x500PrincipalString);

    LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName());

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(StringUtils
                    .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            new X500Name(x500Principal.getName()), // subject,
            new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(false)); // is not a CA certificate

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the digitalSignature usage indicates that the subject public key may be used with a digital signature
            // mechanism to support security services other than non-repudiation, certificate signing, or revocation
            // information signing
            KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures
                                        // used to provide a non-repudiation service which protects against the signing entity falsely denying some
                                        // action, excluding certificate or CRL signing
                    KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the
                                              // exchange of efficient symmetric keys in SSL
                    KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data,
                                               // other than cryptographic keys
                    KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a
                                                // Diffie-Hellman key is to be used for key management
                    KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
                                            // certificates
                    KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                           // information
                    KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL
                                       // client authorization
                    KeyUsage.encipherOnly);
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }
    assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage";

    return x509Certificate;
}

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates a self-signed certificate to use as a CA root certificate.
 *
 * @param keyPair the root public/private key pair
 * @return a self-signed CA root certificate
 *
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */// w  ww  . ja  v  a2  s.  c o  m
protected static X509Certificate generateRootX509Certificate(final KeyPair keyPair)
        throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert keyPair != null : "keyPair must not be null";

    final UUID rootUUID = UUID.randomUUID();
    // provide items to X500Principal in reverse order
    final X500Principal rootX500Principal = new X500Principal(
            "UID=" + rootUUID + ", O=Texai Certification Authority, CN=texai.org");
    final X500Name subject = new X500Name(rootX500Principal.getName());
    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(rootX500Principal.getName()), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(true)); // is a CA certificate with an unlimited certification path length

    final KeyUsage keyUsage = new KeyUsage(
            // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
            // certificates
            KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                   // information
                    KeyUsage.cRLSign);

    // add key usage
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate rootX509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate());
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        rootX509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder);
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        rootX509Certificate.checkValidity();
        rootX509Certificate.verify(keyPair.getPublic());

        return rootX509Certificate;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException
            | CertificateException ex) {
        throw new TexaiException(ex);
    }
}

From source file:org.wildfly.extension.elytron.TlsTestCase.java

License:Apache License

private static X509CRLHolder createCRL() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SelfSignedX509CertificateAndSigningKey muneraSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey
            .builder().setDn(MUNERASOFT_DN).setKeyAlgorithmName("RSA")
            .setSignatureAlgorithmName("SHA256withRSA")
            .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647").build();
    X509Certificate muneraCertificate = muneraSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    calendar.add(Calendar.YEAR, 1);
    Date nextYear = calendar.getTime();
    calendar.add(Calendar.YEAR, -1);
    calendar.add(Calendar.SECOND, -30);
    Date revokeDate = calendar.getTime();

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(MUNERASOFT_DN.getName()), currentDate);
    crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
            new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(muneraCertificate.getPublicKey()));
    crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4110)));
    crlBuilder.addCRLEntry(new BigInteger("1005"), revokeDate, CRLReason.unspecified);
    crlBuilder.addCRLEntry(new BigInteger("1006"), revokeDate, CRLReason.unspecified);
    return crlBuilder.setNextUpdate(nextYear).build(new JcaContentSignerBuilder("SHA256withRSA")
            .setProvider("BC").build(muneraSelfSignedX509CertificateAndSigningKey.getSigningKey()));
}

From source file:org.wildfly.security.ssl.SSLAuthenticationTest.java

License:Open Source License

private static org.bouncycastle.asn1.x500.X500Name convertSunStyleToBCStyle(Principal dn) {
    String dnName = dn.getName();
    String[] dnComponents = dnName.split(", ");
    StringBuilder dnBuffer = new StringBuilder(dnName.length());

    dnBuffer.append(dnComponents[dnComponents.length - 1]);
    for (int i = dnComponents.length - 2; i >= 0; i--) {
        dnBuffer.append(',');
        dnBuffer.append(dnComponents[i]);
    }/*w  w  w. j av  a  2  s  . com*/

    return new X500Name(dnBuffer.toString());
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

    public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
                                                      PKCS10CertificationRequest request,
                                                      String issueSubject)
            throws KeystoreException {

        CommonUtil commonUtil = new CommonUtil();
        Date validityBeginDate = commonUtil.getValidityStartDate();
        Date validityEndDate = commonUtil.getValidityEndDate();

        X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL);
        //X500Name certSubject = request.getSubject();

        Attribute attributes[] = request.getAttributes();

//        if (certSubject == null) {
//            certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//        } else {
//            org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs();
////from  ww  w. j  a va2 s  . c o m
//            if (rdn == null || rdn.length == 0) {
//                certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//            }
//        }


        RDN[] certUniqueIdRDN;
        BigInteger certUniqueIdentifier;

        // IMPORTANT: "Serial-Number" of the certificate used when creating it, is set as its "Alias" to save to
        // keystore.
        if (request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER).length != 0) {
            // if certificate attribute "UNIQUE_IDENTIFIER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else if (request.getSubject().getRDNs(BCStyle.SERIALNUMBER).length != 0) {
            // else if certificate attribute "SERIAL_NUMBER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.SERIALNUMBER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else {
            // else get the BigInteger Value of the integer that is the current system-time in millis as the
            // "Serial-Number".
            certUniqueIdentifier = CommonUtil.generateSerialNumber();
        }

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                new X500Name(issueSubject), certUniqueIdentifier, validityBeginDate, validityEndDate, certSubject,
                request.getSubjectPublicKeyInfo());

        ContentSigner sigGen;
        X509Certificate issuedCert;

        try {
            certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

            if (attributes != null) {
                ASN1Encodable extractedValue = getChallengePassword(attributes);

                if (extractedValue != null) {
                    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true,
                                                    extractedValue);
                }
            }

            sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                    .setProvider(CertificateManagementConstants.PROVIDER).build(privateKey);
            issuedCert = new JcaX509CertificateConverter().setProvider(
                    CertificateManagementConstants.PROVIDER).getCertificate(
                    certificateBuilder.build(sigGen));
            org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate =
                    new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
            List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
            certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
            certificate.setCertificate(issuedCert);
            certificates.add(certificate);
            saveCertInKeyStore(certificates);
        } catch (CertIOException e) {
            String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (OperatorCreationException e) {
            String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (CertificateException e) {
            String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        }

        return issuedCert;
    }

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

License:Open Source License

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *//*www  .  j  a va  2  s  .com*/
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }

}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

License:Open Source License

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *//*  www  .ja  v  a 2  s.c o  m*/
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate);
    storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate);

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER
                + "SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore ["
                + AgentConstants.DEVICE_KEYSTORE + "]");
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }
}