List of usage examples for java.security.cert X509Certificate getExtendedKeyUsage
public List<String> getExtendedKeyUsage() throws CertificateParsingException
From source file:Main.java
public static String[] getExtendedKeyUsage(X509Certificate certificate) throws IOException { try {/*w ww . ja v a2 s . c om*/ List<String> eku = certificate.getExtendedKeyUsage(); if (eku == null) { return null; } return eku.toArray(new String[0]); } catch (GeneralSecurityException gse) { throw new IOException(gse); } }
From source file:Main.java
/** * If an EKU extension is present in the end-entity certificate, it MUST contain either the * anyEKU or serverAuth or netscapeSGC or Microsoft SGC EKUs. * * @return true if there is no EKU extension or if any of the EKU extensions is one of the valid * OIDs for web server certificates./*from w w w.ja va 2s . c om*/ * * TODO(palmer): This can be removed after the equivalent change is made to the Android default * TrustManager and that change is shipped to a large majority of Android users. */ static boolean verifyKeyUsage(X509Certificate certificate) throws CertificateException { List<String> ekuOids; try { ekuOids = certificate.getExtendedKeyUsage(); } catch (NullPointerException e) { // getExtendedKeyUsage() can crash due to an Android platform bug. This probably // happens when the EKU extension data is malformed so return false here. // See http://crbug.com/233610 return false; } if (ekuOids == null) return true; for (String ekuOid : ekuOids) { if (ekuOid.equals(OID_TLS_SERVER_AUTH) || ekuOid.equals(OID_ANY_EKU) || ekuOid.equals(OID_SERVER_GATED_NETSCAPE) || ekuOid.equals(OID_SERVER_GATED_MICROSOFT)) { return true; } } return false; }
From source file:mitm.common.security.certificate.X509CertificateInspector.java
/** * Returns a (possibly empty) set of extended key usage objects, null if there are * no extended key usages. //from w w w .j a va 2s . c om * @throws CertificateParsingException */ public static Set<ExtendedKeyUsageType> getExtendedKeyUsage(X509Certificate certificate) throws CertificateParsingException { Set<ExtendedKeyUsageType> extendedKeyUsages = null; List<String> extendedKeyUsageOIDs = certificate.getExtendedKeyUsage(); if (extendedKeyUsageOIDs != null) { extendedKeyUsages = new HashSet<ExtendedKeyUsageType>(); for (String oid : extendedKeyUsageOIDs) { ExtendedKeyUsageType extKeyUsage = ExtendedKeyUsageType.fromOID(oid); if (extKeyUsage != null) { extendedKeyUsages.add(extKeyUsage); } } } return extendedKeyUsages; }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return null; }// www. j ava 2s . c om LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return null; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return null; } Object responseObject; try { responseObject = ocspResp.getResponseObject(); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; try { X509Certificate[] responseCertificates = basicOCSPResp.getCerts(BouncyCastleProvider.PROVIDER_NAME); for (X509Certificate responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubjectX500Principal()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuerX500Principal()); } TrustLinkerResult trustResult = TrustValidator .checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgName()); if (!trustResult.isValid()) return trustResult; if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the * issuing CA itself. */ boolean verificationResult = basicOCSPResp.verify(certificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return null; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509Certificate ocspResponderCertificate = responseCertificates[0]; boolean verificationResult = basicOCSPResp.verify(ocspResponderCertificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return null; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(ocspResponderCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly * signed by the CA. */ issuingCaCertificate = certificate; } else { issuingCaCertificate = responseCertificates[1]; /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return null; } } // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); trustResult = publicKeyTrustLinker.hasTrustLink(ocspResponderCertificate, issuingCaCertificate, validationDate, revocationData); if (null != trustResult) { if (!trustResult.isValid()) { LOG.debug("OCSP responder not trusted"); return null; } } if (null == ocspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return null; } List<String> extendedKeyUsage; try { extendedKeyUsage = ocspResponderCertificate.getExtendedKeyUsage(); } catch (CertificateParsingException e) { LOG.debug("OCSP Responder parsing error: " + e.getMessage(), e); return null; } if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return null; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return null; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); } } } catch (NoSuchProviderException e) { LOG.debug("JCA provider exception: " + e.getMessage(), e); return null; } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } catch (CertificateEncodingException e) { LOG.debug("certificate encoding error: " + e.getMessage(), e); return null; } CertificateID certificateId; try { certificateId = new CertificateID(CertificateID.HASH_SHA1, certificate, childCertificate.getSerialNumber()); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } Date thisUpdate = singleResp.getThisUpdate(); LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); long dt = Math.abs(thisUpdate.getTime() - validationDate.getTime()); if (dt > this.freshnessInterval) { LOG.warn("freshness interval exceeded: " + dt + " milliseconds"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(true); } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return null; }
From source file:org.cesecore.util.CertTools.java
/** * Is OCSP extended key usage set for a certificate? * /*from w w w. j av a 2 s . com*/ * @param cert to check. * @return true if the extended key usage for OCSP is check */ public static boolean isOCSPCert(X509Certificate cert) { final List<String> keyUsages; try { keyUsages = cert.getExtendedKeyUsage(); } catch (CertificateParsingException e) { return false; } return keyUsages != null && keyUsages.contains(KeyPurposeId.id_kp_OCSPSigning.getId()); }
From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java
@Test public void test07ExtensionOverride() throws Exception { byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); // Create some crazy extensions to see that we get them when using // extension override. // We should not get our values when not using extension override ExtensionsGenerator extgen = new ExtensionsGenerator(); // SubjectAltName GeneralNames san = CertTools.getGeneralNamesFromAltName("dnsName=foo.bar.com"); extgen.addExtension(Extension.subjectAlternativeName, false, san); // KeyUsage//from w w w . j av a 2 s . co m int bcku = 0; bcku = X509KeyUsage.decipherOnly; X509KeyUsage ku = new X509KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, ku); // Extended Key Usage List<KeyPurposeId> usage = new ArrayList<KeyPurposeId>(); usage.add(KeyPurposeId.id_kp_codeSigning); ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(usage); extgen.addExtension(Extension.extendedKeyUsage, false, eku); // OcspNoCheck extgen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE); // Netscape cert type extgen.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false, new NetscapeCertType(NetscapeCertType.objectSigningCA)); // My completely own extgen.addExtension(new ASN1ObjectIdentifier("1.1.1.1.1"), false, new DERIA5String("PrimeKey")); // Make the complete extension package Extensions exts = extgen.generate(); // First test without extension override PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null, null, null, null); PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId); String altNames = CertTools.getSubjectAlternativeName(cert); assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1); // Check key usage that it is nonRepudiation for KeyId2 boolean[] kubits = cert.getKeyUsage(); assertFalse(kubits[0]); assertTrue(kubits[1]); assertFalse(kubits[2]); assertFalse(kubits[3]); assertFalse(kubits[4]); assertFalse(kubits[5]); assertFalse(kubits[6]); assertFalse(kubits[7]); assertFalse(kubits[8]); // Our own ext should not be here assertNull(cert.getExtensionValue("1.1.1.1.1")); assertNull(cert.getExtensionValue("2.16.840.1.113730.1.1")); assertNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); // Skip confirmation message, we have tested that several times already // // Do the same with keyId4, that has full extension override one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null, null, null, null); req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId4", 567); ir = (CertReqMessages) req.getBody().getContent(); reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(req); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId); altNames = CertTools.getSubjectAlternativeName(cert); assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1); // Check key usage that it is decipherOnly for KeyId4 kubits = cert.getKeyUsage(); assertFalse(kubits[0]); assertFalse(kubits[1]); assertFalse(kubits[2]); assertFalse(kubits[3]); assertFalse(kubits[4]); assertFalse(kubits[5]); assertFalse(kubits[6]); assertFalse(kubits[7]); assertTrue(kubits[8]); // Our own ext should not be here assertNotNull(cert.getExtensionValue("1.1.1.1.1")); assertNotNull(cert.getExtensionValue("2.16.840.1.113730.1.1")); assertNotNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); List<String> l = cert.getExtendedKeyUsage(); assertEquals(1, l.size()); String s = l.get(0); assertEquals(KeyPurposeId.id_kp_codeSigning.getId(), s); // Skip confirmation message, we have tested that several times already }
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 w w w.ja v a 2 s . co 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.ejbca.ui.web.CertificateView.java
public String[] getExtendedKeyUsageAsTexts() { List<String> extendedkeyusage = null; if (certificate instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) certificate; try {//from ww w . ja v a 2 s . c o m extendedkeyusage = x509cert.getExtendedKeyUsage(); } catch (java.security.cert.CertificateParsingException e) { } } if (extendedkeyusage == null) { extendedkeyusage = new ArrayList<String>(); } String[] returnval = new String[extendedkeyusage.size()]; Map<String, String> map = CertificateProfile.getAllExtendedKeyUsageTexts(); for (int i = 0; i < extendedkeyusage.size(); i++) { returnval[i] = (String) map.get(extendedkeyusage.get(i)); } return returnval; }