Example usage for java.security.cert X509Certificate getType

List of usage examples for java.security.cert X509Certificate getType

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getType.

Prototype

public final String getType() 

Source Link

Document

Returns the type of this certificate.

Usage

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static SocketFactory createSocketFactory(InputStream keyStore, String password,
        String keystoreType, String algorithm, String protocol)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException, CertificateExpiredException {

    char[] pwdChars = password.toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(keyStore, pwdChars);//from  w ww  . ja v a2s  .co  m

    // ??
    Enumeration<String> enums = ks.aliases();
    String alias = "";
    if (enums.hasMoreElements()) {
        alias = enums.nextElement();
    }
    if (StringUtils.isNotEmpty(alias)) {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        if (null != certificate) {
            String type = certificate.getType();
            int ver = certificate.getVersion();
            String name = certificate.getSubjectDN().getName();
            String serialNumber = certificate.getSerialNumber().toString(16);
            String issuerDN = certificate.getIssuerDN().getName();
            String sigAlgName = certificate.getSigAlgName();
            String publicAlgorithm = certificate.getPublicKey().getAlgorithm();
            Date before = certificate.getNotBefore();
            Date after = certificate.getNotAfter();

            String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss");
            String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss");

            // ??
            long expire = DateUtil.getNumberOfDaysBetween(new Date(), after);
            if (expire <= 0) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(
                            "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]",
                            name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                            afterStr, Math.abs(expire));
                }

                throw new CertificateExpiredException("??[" + Math.abs(expire) + "]");
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(
                        "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?",
                        name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                        afterStr, expire);
            }
        }
    }

    KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm);
    kf.init(ks, pwdChars);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init((KeyStore) null);
    SSLContext context = SSLContext.getInstance(protocol);
    context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a {@code Certificate} with the received data.
 *
 * @param keypair/*from w  w  w . ja va2 s. c om*/
 *            key pair for the certificate
 * @param issuer
 *            issuer for the certificate
 * @return a {@code Certificate} with the received data
 * @throws IOException
 *             if there is an I/O or format problem with the certificate
 *             data
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 * @throws InvalidKeyException
 *             if there was a problem with the key
 * @throws NoSuchAlgorithmException
 *             if an algorithm required to create the key store could not be
 *             found
 * @throws NoSuchProviderException
 *             if a required provider is missing
 * @throws SignatureException
 *             if any problem occurs while signing the certificate
 */
private final Certificate getCertificate(final KeyPair keypair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    final X509v3CertificateBuilder builder; // Certificate builder
    final X509Certificate certificate; // Certificate

    // Generates the certificate builder
    builder = getCertificateBuilder(keypair.getPublic(), issuer);

    // Generates the signed certificate
    certificate = getSignedCertificate(builder, keypair.getPrivate());

    // Verifies the certificate
    certificate.checkValidity(getCurrentDate());
    certificate.verify(keypair.getPublic());

    LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(),
            Arrays.asList(certificate.getEncoded()));
    LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey());

    return certificate;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public List<TokenCertificateResponseWS> genTokenCertificates(UserDataVOWS userDataWS,
        List<TokenCertificateRequestWS> tokenRequests, HardTokenDataWS hardTokenDataWS,
        boolean overwriteExistingSN, boolean revokePreviousCards)
        throws CADoesntExistsException, AuthorizationDeniedException, WaitingForApprovalException,
        HardTokenExistsException, UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException,
        ApprovalRequestExpiredException, ApprovalRequestExecutionException {
    final ArrayList<TokenCertificateResponseWS> retval = new ArrayList<TokenCertificateResponseWS>();

    final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession,
            caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession,
            endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);
    AuthenticationToken admin = ejbhelper.getAdmin(true);
    int endEntityProfileId = 0;
    boolean hardTokenExists = false;
    boolean userExists = false;

    boolean approvalSuccessfullStep1 = false;
    boolean isRejectedStep1 = false;

    // Get Significant user Id
    final CAInfo significantcAInfo;
    final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);/*from  ww  w.  j a va  2 s  . c  o  m*/
    final AuthenticationToken intAdmin = new AlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("EJBCAWS.genTokenCertificates"));
    try {
        significantcAInfo = caSession.getCAInfo(intAdmin, userDataWS.getCaName());
        if (significantcAInfo == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    "Error the given CA : " + userDataWS.getCaName() + " could not be found.", logger,
                    ErrorCode.CA_NOT_EXISTS, null);
        }

        EndEntityInformation endEntityInformation = endEntityAccessSession.findUser(intAdmin,
                userDataWS.getUsername());
        if (endEntityInformation != null) {
            endEntityProfileId = endEntityInformation.getEndEntityProfileId();
            userExists = true;
        } else {
            try {
                endEntityProfileId = endEntityProfileSession
                        .getEndEntityProfileId(userDataWS.getEndEntityProfileName());
            } catch (EndEntityProfileNotFoundException e) {
                throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : "
                        + userDataWS.getEndEntityProfileName() + " could not be found", logger,
                        ErrorCode.EE_PROFILE_NOT_EXISTS, null);
            }
        }

        // Approval request if we require approvals to generate token certificates
        ApprovalRequest ar = null;
        if (ejbhelper.isAdmin()) {
            final List<String> rules = new ArrayList<String>();
            rules.add(StandardRules.CREATECERT.resource());
            rules.add(AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS);
            rules.add(StandardRules.CAACCESS.resource() + significantcAInfo.getCAId());
            if (overwriteExistingSN) {
                rules.add(AccessRulesConstants.REGULAR_REVOKEENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.REVOKE_END_ENTITY);
            }
            if (userExists) {
                rules.add(AccessRulesConstants.REGULAR_EDITENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.EDIT_END_ENTITY);
            } else {
                rules.add(AccessRulesConstants.REGULAR_CREATEENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.CREATE_END_ENTITY);
            }
            String[] rulesArray = rules.toArray(new String[rules.size()]);
            if (!authorizationSession.isAuthorizedNoLogging(admin, rulesArray)) {
                final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource",
                        Arrays.toString(rulesArray), null);
                throw new AuthorizationDeniedException(msg);
            }
        } else {
            if (WebServiceConfiguration.getApprovalForGenTokenCertificates()) {
                ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(),
                        hardTokenDataWS.getLabel(), admin, null,
                        WebServiceConfiguration.getNumberOfRequiredApprovals(), significantcAInfo.getCAId(),
                        endEntityProfileId);
                int status = ApprovalDataVO.STATUS_REJECTED;
                try {
                    status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
                    approvalSuccessfullStep1 = (status == ApprovalDataVO.STATUS_APPROVED);
                    isRejectedStep1 = (status == ApprovalDataVO.STATUS_REJECTED);
                    if (status == ApprovalDataVO.STATUS_APPROVED) {
                        ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin,
                                ar.generateApprovalId());
                        String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest())
                                .getDN();
                        userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
                    } else if (status == ApprovalDataVO.STATUS_REJECTED) {
                        throw new ApprovalRequestExecutionException(
                                "The approval for id " + ar.generateApprovalId() + " has been rejected.");
                    } else if (status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                            || status == ApprovalDataVO.STATUS_EXPIRED) {
                        throw new ApprovalException(
                                "The approval for id " + ar.generateApprovalId() + " has expired.");
                    } else {
                        throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId()
                                + " have not yet been approved", ar.generateApprovalId());
                    }
                } catch (ApprovalException e) {
                    approvalSession.addApprovalRequest(admin, ar);
                    throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId()
                            + " have been added for approval.", ar.generateApprovalId());
                }
            } else {
                throw new AuthorizationDeniedException();
            }
        }

        if (ar != null && isRejectedStep1) {
            throw new ApprovalRequestExecutionException(
                    "The approval for id " + ar.generateApprovalId() + " has been rejected.");
        }

        if (ar != null && !approvalSuccessfullStep1) {
            throw new WaitingForApprovalException(
                    "The approval for id " + ar.generateApprovalId() + " has not yet been approved",
                    ar.generateApprovalId());
        }

        if (ar != null) {
            // We need to create a new AuthenticationToken here that has the "name" of the admin making the request, but that 
            // behaves like an "AlwaysAllowedAuthenticationToken". This is because the request admin does not have privileges, 
            // but we want to log as if the requesting admin performed actions below.
            final Set<? extends Principal> principals = admin.getPrincipals();
            Principal p = null;
            if (!principals.isEmpty()) {
                p = principals.iterator().next();
            } else {
                final Set<?> credentials = admin.getCredentials();
                if (!credentials.isEmpty()) {
                    final Object o = credentials.iterator().next();
                    if (o instanceof X509Certificate) {
                        final X509Certificate cert = (X509Certificate) o;
                        p = new X500Principal(cert.getSubjectDN().getName());
                    }
                } else {
                    log.error("Admin does not have neither Principals nor Credentials");
                }
            }
            admin = new AlwaysAllowLocalAuthenticationToken(p);
        }

        hardTokenExists = hardTokenSession.existsHardToken(hardTokenDataWS.getHardTokenSN());
        if (hardTokenExists) {
            if (overwriteExistingSN) {
                // fetch all old certificates and revoke them.
                Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession
                        .findCertificatesInHardToken(hardTokenDataWS.getHardTokenSN());
                HardTokenInformation currentHardToken = hardTokenSession.getHardToken(admin,
                        hardTokenDataWS.getHardTokenSN(), false);
                Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
                while (iter.hasNext()) {
                    java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter
                            .next();
                    try {
                        endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(nextCert),
                                CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
                    } catch (AlreadyRevokedException e) {
                        // Ignore previously revoked certificates
                    } catch (FinderException e) {
                        throw EjbcaWSHelper.getEjbcaException(
                                "Error revoking old certificate, the user : " + currentHardToken.getUsername()
                                        + " of the old certificate couldn't be found in database.",
                                logger, ErrorCode.USER_NOT_FOUND, null);
                    }
                }

            } else {
                throw new HardTokenExistsException(
                        "Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
            }

        }

        if (revokePreviousCards) {
            List<HardTokenDataWS> htd = getHardTokenDatas(admin, userDataWS.getUsername(), false, true, logger);
            Iterator<HardTokenDataWS> htdIter = htd.iterator();

            while (htdIter.hasNext()) {
                HardTokenDataWS toRevoke = htdIter.next();
                try {
                    if (hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)
                            && toRevoke.getLabel() != null
                            && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)) {

                        // Token have extended key usage MS Logon, don't revoke it
                        Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession
                                .findCertificatesInHardToken(toRevoke.getHardTokenSN()).iterator();

                        while (revokeCerts.hasNext()) {
                            X509Certificate next = (X509Certificate) revokeCerts.next();
                            try {
                                if (WebServiceConfiguration.getSuspendAllCertificates()
                                        || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage()
                                                .contains(KeyPurposeId.id_kp_smartcardlogon.getId())) {
                                    endEntityManagementSession.revokeCert(admin, next.getSerialNumber(),
                                            CertTools.getIssuerDN(next),
                                            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                                }
                            } catch (CertificateParsingException e) {
                                log.error(e);
                            } catch (FinderException e) {
                                log.error(e);
                            }
                        }

                    } else {
                        revokeToken(admin, toRevoke.getHardTokenSN(),
                                RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
                    }
                } catch (AlreadyRevokedException e) {
                    // Do nothing
                }
            }
        }

        try {
            // Check if the userdata exist and edit/add it depending on which
            String password = PasswordGeneratorFactory
                    .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
            EndEntityInformation userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
            userData.setPassword(password);
            if (userExists) {
                endEntityManagementSession.changeUser(admin, userData, true);
            } else {
                endEntityManagementSession.addUser(admin, userData, true);
            }

            Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));

            Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
            while (iter.hasNext()) {
                TokenCertificateRequestWS next = iter.next();

                int certificateProfileId = certificateProfileSession
                        .getCertificateProfileId(next.getCertificateProfileName());
                if (certificateProfileId == 0) {
                    EjbcaWSHelper
                            .getEjbcaException(
                                    "Error the given Certificate Profile : " + next.getCertificateProfileName()
                                            + " couldn't be found.",
                                    logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
                }

                Date eDate = null;

                if (next.getValidityIdDays() != null) {
                    try {
                        long validity = Long.parseLong(next.getValidityIdDays());
                        eDate = new Date(System.currentTimeMillis() + (validity * 3600 * 24 * 1000));
                    } catch (NumberFormatException e) {
                        EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number", logger,
                                ErrorCode.BAD_VALIDITY_FORMAT, null);
                    }
                }

                CAInfo cAInfo = caSession.getCAInfo(admin, next.getCAName());
                if (cAInfo == null) {
                    throw EjbcaWSHelper.getEjbcaException(
                            "Error the given CA : " + next.getCAName() + " couldn't be found.", logger,
                            ErrorCode.CA_NOT_EXISTS, null);
                }

                if (!authorizationSession.isAuthorizedNoLogging(admin,
                        StandardRules.CAACCESS.resource() + cAInfo.getCAId())) {
                    final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource",
                            StandardRules.CAACCESS.resource() + cAInfo.getCAId(), null);
                    throw new AuthorizationDeniedException(msg);
                }
                if (next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST) {
                    userData.setCertificateProfileId(certificateProfileId);
                    userData.setCAId(cAInfo.getCAId());
                    userData.setPassword(password);
                    userData.setStatus(EndEntityConstants.STATUS_NEW);
                    endEntityManagementSession.changeUser(admin, userData, false);
                    PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
                    java.security.cert.Certificate cert;
                    if (eDate == null) {
                        cert = signSession.createCertificate(admin, userData.getUsername(), password,
                                pkcs10req.getRequestPublicKey());
                    } else {
                        cert = signSession.createCertificate(admin, userData.getUsername(), password,
                                pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
                    }

                    genCertificates.add(cert);
                    retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
                } else if (next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST) {

                    if (!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)) {
                        throw EjbcaWSHelper.getEjbcaException(
                                "Unsupported Key Store Type : " + next.getTokenType() + " only "
                                        + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
                                logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
                    }
                    KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());
                    userData.setCertificateProfileId(certificateProfileId);
                    userData.setCAId(cAInfo.getCAId());
                    userData.setPassword(password);
                    userData.setStatus(EndEntityConstants.STATUS_NEW);
                    endEntityManagementSession.changeUser(admin, userData, true);
                    X509Certificate cert;
                    if (eDate == null) {
                        cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(),
                                password, keys.getPublic());
                    } else {
                        cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(),
                                password, keys.getPublic(), -1, bDate, eDate);
                    }

                    genCertificates.add(cert);
                    // Generate Keystore
                    // Fetch CA Cert Chain.           
                    Collection<java.security.cert.Certificate> chain = caSession
                            .getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
                    String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
                    if (alias == null) {
                        alias = userData.getUsername();
                    }
                    java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);

                    retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword())));
                } else {
                    throw EjbcaWSHelper.getEjbcaException(
                            "Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.",
                            logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null);
                }
            }

        } catch (Exception e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            endEntityManagementSession.setUserStatus(admin, userDataWS.getUsername(),
                    EndEntityConstants.STATUS_GENERATED);
        }

        // Add hard token data
        HardToken hardToken;
        String signatureInitialPIN = "";
        String signaturePUK = "";
        String basicInitialPIN = "";
        String basicPUK = "";
        Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator();
        while (iter.hasNext()) {
            PinDataWS pinData = iter.next();
            switch (pinData.getType()) {
            case HardTokenConstants.PINTYPE_BASIC:
                basicInitialPIN = pinData.getInitialPIN();
                basicPUK = pinData.getPUK();
                break;
            case HardTokenConstants.PINTYPE_SIGNATURE:
                signatureInitialPIN = pinData.getInitialPIN();
                signaturePUK = pinData.getPUK();
                break;
            default:
                throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(), logger,
                        ErrorCode.NOT_SUPPORTED_PIN_TYPE, null);
            }
        }
        int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE;
        switch (hardTokenDataWS.getTokenType()) {
        case HardTokenConstants.TOKENTYPE_SWEDISHEID:
            hardToken = new SwedishEIDHardToken(basicInitialPIN, basicPUK, signatureInitialPIN, signaturePUK,
                    0);
            break;
        case HardTokenConstants.TOKENTYPE_ENHANCEDEID:
            hardToken = new EnhancedEIDHardToken(signatureInitialPIN, signaturePUK, basicInitialPIN, basicPUK,
                    false, 0);
            tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE;
            break;
        default:
            throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(),
                    logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null);

        }

        hardToken.setLabel(hardTokenDataWS.getLabel());
        if (overwriteExistingSN) {
            if (hardTokenExists) {
                try {
                    hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN());
                } catch (HardTokenDoesntExistsException e) {
                    throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS,
                            Level.ERROR);
                }
            }
        }
        hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(),
                significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates,
                hardTokenDataWS.getCopyOfSN());

        if (ar != null) {
            approvalSession.markAsStepDone(admin, ar.generateApprovalId(),
                    GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN);
        }
    } catch (FinderException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (RuntimeException e) { // EJBException, ClassCastException, ...
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
    return retval;
}

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

@Test(description = "This test case tests generation of X509Certificate")
public void testGenerateX509Certificate() throws KeystoreException {
    X509Certificate x509Certificate = managementService.generateX509Certificate();
    Assert.assertNotNull(x509Certificate);
    Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
    log.info("GenerateX509Certificate Test Successful");
}

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

@Test(description = "This test case tests generation of a X509Certificate from a CSR")
public void testGenerateCertificateFromCSR() throws KeystoreException, IOException {
    CSRGenerator csrGeneration = new CSRGenerator();
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    // Generate key pair
    KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
    byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
    PKCS10CertificationRequest certificationRequest;
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
    certificationRequest = new PKCS10CertificationRequest(csrData);
    X509Certificate x509Certificate = managementService.generateCertificateFromCSR(privateKeyCA,
            certificationRequest, certCA.getIssuerX500Principal().getName());
    Assert.assertNotNull(x509Certificate);
    Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
    log.info("GenerateCertificateFromCSR Test Successful");
}

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

@Test(description = "This test case tests generation of signed Certificate from a CSR")
public void testGetSignedCertificateFromCSR() throws KeystoreException {
    CSRGenerator csrGeneration = new CSRGenerator();
    BASE64Encoder encoder = new BASE64Encoder();
    // Generate key pair
    KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
    byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
    X509Certificate signedCertificateFromCSR = managementService
            .getSignedCertificateFromCSR(encoder.encode(csrData));
    Assert.assertNotNull(signedCertificateFromCSR);
    Assert.assertEquals(signedCertificateFromCSR.getType(), CertificateManagementConstants.X_509);
    log.info("GetSignedCertificateFromCSR Test Successful");
}

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

@Test(description = "This test case tests converting a pem file to X509 Certificate")
public void testPemToX509Certificate() throws IOException, KeystoreException {
    File caCert = new File(CA_CERT_PEM);
    BASE64Encoder encoder = new BASE64Encoder();
    byte[] caBytes = FileUtils.readFileToByteArray(caCert);
    X509Certificate certificate = managementService.pemToX509Certificate(encoder.encode(caBytes));
    Assert.assertNotNull(certificate);//from  w ww.  ja  v  a 2s .com
    Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
    log.info("PemToX509Certificate Test Successful");
}

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

@Test(description = "This test case tests extracting Certificate from the header Signature")
public void testExtractCertificateFromSignature()
        throws KeystoreException, CertificateEncodingException, CMSException, IOException {
    BASE64Encoder encoder = new BASE64Encoder();
    //generate and save a certificate in the keystore
    X509Certificate x509Certificate = managementService.generateX509Certificate();
    //Generate CMSdata
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    List<X509Certificate> list = new ArrayList<>();
    list.add(x509Certificate);/*from w  w  w .jav  a  2s.c  om*/
    JcaCertStore store = new JcaCertStore(list);
    generator.addCertificates(store);
    CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
    byte[] signature = degenerateSd.getEncoded();
    X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature));
    Assert.assertNotNull(certificate);
    Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
    log.info("ExtractCertificateFromSignature Test Successful");
}