List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:be.fedict.eid.tsl.TrustServiceList.java
private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {//from ww w.j a v a 2s . com XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); LOG.debug("xml signature factory: " + signatureFactory.getClass().getName()); LOG.debug("loader: " + signatureFactory.getClass().getClassLoader()); XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Reference> references = new LinkedList<Reference>(); List<Transform> transforms = new LinkedList<Transform>(); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null); references.add(reference); String signatureId = "xmldsig-" + UUID.randomUUID().toString(); List<XMLObject> objects = new LinkedList<XMLObject>(); addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects); SignatureMethod signatureMethod; if (isJava6u18OrAbove()) { signatureMethod = signatureFactory .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); } else { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); x509DataObjects.add(certificate); x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(), certificate.getSerialNumber())); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); String signatureValueId = signatureId + "-signature-value"; XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); xmlSignature.sign(signContext); }
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.j ava 2s . c om 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:be.fedict.eid.dss.ws.DSSUtil.java
/** * Adds a DSS Verification Report to specified optional output element from * the specified list of {@link SignatureInfo}'s * /*from ww w .j av a2s . c o m*/ * @param optionalOutput * optional output to add verification report to * @param signatureInfos * signature infos to use in verification report. */ public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) { LOG.debug("return verification report"); VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType(); List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (SignatureInfo signatureInfo : signatureInfos) { X509Certificate signerCertificate = signatureInfo.getSigner(); IndividualReportType individualReport = vrObjectFactory.createIndividualReportType(); individualReports.add(individualReport); SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType(); individualReport.setSignedObjectIdentifier(signedObjectIdentifier); SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType(); signedObjectIdentifier.setSignedProperties(signedProperties); SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(signatureInfo.getSigningTime()); signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult(); individualReport.setResult(individualResult); individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS); individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType(); individualReport.setDetails(details); DetailedSignatureReportType detailedSignatureReport = vrObjectFactory .createDetailedSignatureReportType(); details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport)); VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType(); formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); detailedSignatureReport.setFormatOK(formatOKVerificationResult); SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType(); detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity); VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType(); signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult); sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); if (null != signatureInfo.getRole()) { PropertiesType properties = vrObjectFactory.createPropertiesType(); detailedSignatureReport.setProperties(properties); SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType(); properties.setSignedProperties(vrSignedProperties); SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties); vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); SignerRoleType signerRole = vrObjectFactory.createSignerRoleType(); vrSignedSignatureProperties.setSignerRole(signerRole); ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType(); signerRole.setClaimedRoles(claimedRolesList); be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory .createAnyType(); claimedRolesList.getClaimedRole().add(claimedRoleAny); claimedRoleAny.getContent().add(signatureInfo.getRole()); } CertificatePathValidityType certificatePathValidity = vrObjectFactory .createCertificatePathValidityType(); detailedSignatureReport.setCertificatePathValidity(certificatePathValidity); VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType(); certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); certificatePathValidity.setPathValiditySummary(certPathVerificationResult); X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType(); certificatePathValidity.setCertificateIdentifier(certificateIdentifier); certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString()); certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber()); CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory .createCertificatePathValidityVerificationDetailType(); certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail); CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType(); certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity); certificateValidity.setCertificateIdentifier(certificateIdentifier); certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString()); VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setChainingOK(chainingOkVerificationResult); chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory .createVerificationResultType(); certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult); validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setExtensionsOK(extensionsOkVerificationResult); extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); try { certificateValidity.setCertificateValue(signerCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("X509 encoding error: " + e.getMessage(), e); } certificateValidity.setSignatureOK(signatureOkSignatureValidity); CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType(); certificateValidity.setCertificateStatus(certificateStatus); VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateStatus.setCertStatusOK(certStatusOkVerificationResult); certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); } Document newDocument = documentBuilder.newDocument(); Element newElement = newDocument.createElement("newNode"); try { vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement); } catch (JAXBException e) { throw new RuntimeException("JAXB error: " + e.getMessage(), e); } Element verificationReportElement = (Element) newElement.getFirstChild(); optionalOutput.getAny().add(verificationReportElement); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void keyRecover() throws Exception { log.trace(">keyRecover"); GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean krenabled = gc.getEnableKeyRecovery(); if (krenabled == true) { gc.setEnableKeyRecovery(false);/*from w ww.ja va 2 s .c o m*/ globalConfigurationSession.saveConfiguration(intAdmin, gc); } boolean trows = false; try { // This should throw an exception that key recovery is not enabled ejbcaraws.keyRecoverNewest(CA1_WSTESTUSER1); } catch (EjbcaException_Exception e) { trows = true; // e.printStackTrace(); assertEquals(e.getMessage(), "Keyrecovery have to be enabled in the system configuration in order to use this command."); } assertTrue(trows); // Set key recovery enabled gc.setEnableKeyRecovery(true); globalConfigurationSession.saveConfiguration(intAdmin, gc); trows = false; try { // This should throw an exception that the user does not exist ejbcaraws.keyRecoverNewest("sdfjhdiuwerw43768754###"); } catch (NotFoundException_Exception e) { trows = true; // e.printStackTrace(); assertEquals(e.getMessage(), "Wrong username or password"); } assertTrue(trows); // Add a new End entity profile, KEYRECOVERY EndEntityProfile profile = new EndEntityProfile(); profile.addField(DnComponents.COMMONNAME); profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true); profile.setValue(EndEntityProfile.KEYRECOVERABLE, 0, EndEntityProfile.TRUE); profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true); profile.setUse(EndEntityProfile.CLEARTEXTPASSWORD, 0, true); profile.setReUseKeyRecoveredCertificate(true); profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS)); endEntityProfileSession.addEndEntityProfile(intAdmin, "KEYRECOVERY", profile); assertTrue("Unable to create KEYRECOVERY end entity profile.", endEntityProfileSession.getEndEntityProfile("KEYRECOVERY") != null); // Add a new user, set token to P12, status to new and end entity // profile to key recovery UserDataVOWS user1 = new UserDataVOWS(); user1.setKeyRecoverable(true); user1.setUsername("WSTESTUSERKEYREC1"); user1.setPassword("foo456"); user1.setClearPwd(true); user1.setSubjectDN("CN=WSTESTUSERKEYREC1"); user1.setCaName(getAdminCAName()); user1.setEmail(null); user1.setSubjectAltName(null); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12); user1.setEndEntityProfileName("KEYRECOVERY"); user1.setCertificateProfileName("ENDUSER"); ejbcaraws.editUser(user1); KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC1", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks); Enumeration<String> en = ks.aliases(); String alias = en.nextElement(); if (!ks.isKeyEntry(alias)) { alias = en.nextElement(); } X509Certificate cert = (X509Certificate) ks.getCertificate(alias); assertEquals("CN=WSTESTUSERKEYREC1", cert.getSubjectDN().toString()); PrivateKey privK = (PrivateKey) ks.getKey(alias, "foo456".toCharArray()); // This should work now ejbcaraws.keyRecoverNewest("WSTESTUSERKEYREC1"); // Set status to keyrecovery UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue("WSTESTUSERKEYREC1"); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null); assertTrue(userdatas.size() == 1); userdatas.get(0).setStatus(EndEntityConstants.STATUS_KEYRECOVERY); ejbcaraws.editUser(userdatas.get(0)); // A new PK12 request now should return the same key and certificate KeyStore ksenv2 = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC1", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex if (!ks2.isKeyEntry(alias)) { alias = (String) en.nextElement(); } X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC1"); PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Compare certificates assertEquals(cert.getSerialNumber().toString(16), cert2.getSerialNumber().toString(16)); // Compare keys String key1 = new String(Hex.encode(privK.getEncoded())); String key2 = new String(Hex.encode(privK2.getEncoded())); assertEquals(key1, key2); log.trace("<keyRecover"); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs12() throws Exception { log.trace(">generatePkcs12"); boolean exceptionThrown = false; try {/*from w ww. ja v a 2 s . c o m*/ ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown);// Should fail // Change token to P12 UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertNotNull(userdatas); assertEquals(1, userdatas.size()); userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_P12); userdatas.get(0).setSubjectDN(getDN(CA1_WSTESTUSER1)); ejbcaraws.editUser(userdatas.get(0)); exceptionThrown = false; try { ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); // Should fail // Change password to foo456 and status to NEW userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword("foo456"); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); KeyStore ksenv = null; try { ksenv = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { assertTrue(e.getMessage(), false); } assertNotNull(ksenv); java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks); Enumeration<String> en = ks.aliases(); String alias = en.nextElement(); X509Certificate cert = (X509Certificate) ks.getCertificate(alias); assertEquals(cert.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); PrivateKey privK1 = (PrivateKey) ks.getKey(alias, "foo456".toCharArray()); log.info("test04GeneratePkcs12() Certificate " + cert.getSubjectDN().toString() + " equals " + getDN(CA1_WSTESTUSER1)); // Generate a new one and make sure it is a new one and that key // recovery does not kick in by mistake // Set status to new usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null); assertTrue(userdatas.size() == 1); userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword("foo456"); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); // A new PK12 request now should return the same key and certificate KeyStore ksenv2 = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Compare certificates, must not be the same assertFalse(cert.getSerialNumber().toString(16).equals(cert2.getSerialNumber().toString(16))); // Compare keys, must not be the same String key1 = new String(Hex.encode(privK1.getEncoded())); String key2 = new String(Hex.encode(privK2.getEncoded())); assertFalse(key1.equals(key2)); // Test the method for adding/editing and requesting a PKCS#12 KeyStore // in a single transaction ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Test the method for adding/editing and requesting a JKS KeyStore in a // single transaction userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_JKS); ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "JKS", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectX500Principal().getName(), getReversedDN(CA1_WSTESTUSER1)); privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); log.trace("<generatePkcs12"); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** * This test tests that the OCSP response contains the extension "id_pkix_ocsp_archive_cutoff" if "ocsp.expiredcert.retentionperiod" * is set in the condfiguration file/*from ww w. j a v a 2 s . c o m*/ * * @throws Exception */ @Test public void testExpiredCertArchiveCutoffExtension() throws Exception { final String username = "expiredCertUsername"; String cpname = "ValidityCertProfile"; String eepname = "ValidityEEProfile"; X509Certificate xcert = null; CertificateProfileSessionRemote certProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateProfileSessionRemote.class); EndEntityProfileSessionRemote eeProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityProfileSessionRemote.class); try { if (certProfSession.getCertificateProfile(cpname) == null) { final CertificateProfile cp = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.setAllowValidityOverride(true); try { certProfSession.addCertificateProfile(admin, cpname, cp); } catch (CertificateProfileExistsException e) { log.error("Certificate profile exists: ", e); } } final int cpId = certProfSession.getCertificateProfileId(cpname); if (eeProfSession.getEndEntityProfile(eepname) == null) { final EndEntityProfile eep = new EndEntityProfile(true); eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId); try { eeProfSession.addEndEntityProfile(admin, eepname, eep); } catch (EndEntityProfileExistsException e) { log.error("Could not create end entity profile.", e); } } final int eepId = eeProfSession.getEndEntityProfileId(eepname); if (!endEntityManagementSession.existsUser(username)) { endEntityManagementSession.addUser(admin, username, "foo123", "CN=expiredCertUsername", null, "ocsptest@anatom.se", false, eepId, cpId, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid); log.debug("created user: expiredCertUsername, foo123, CN=expiredCertUsername"); } else { log.debug("User expiredCertUsername already exists."); EndEntityInformation userData = new EndEntityInformation(username, "CN=expiredCertUsername", caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), eepId, cpId, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); } // Generate certificate for the new user KeyPair keys = KeyTools.genKeys("512", "RSA"); long now = (new Date()).getTime(); long notAfter = now + 1000; xcert = (X509Certificate) signSession.createCertificate(admin, username, "foo123", new PublicKeyWrapper(keys.getPublic()), -1, new Date(), new Date(notAfter)); assertNotNull("Failed to create new certificate", xcert); Thread.sleep(2000L); // wait for the certificate to expire // -------- Testing with default config value OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); OCSPReq req = gen.build(); BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); SingleResp resp = response.getResponses()[0]; Extension singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); ASN1GeneralizedTime extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); long expectedValue = (new Date()).getTime() - (31536000L * 1000); long actualValue = extvalue.getDate().getTime(); long diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); // -------- Send a request where id_pkix_ocsp_archive_cutoff SHOULD NOT be used // set ocsp configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "-1"); this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNull("The wrong extension was sent with reply", singleExtension); // ------------ Send a request where id_pkix_ocsp_archive_cutoff SHOULD be used // set ocsp configuration map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "63072000"); // 2 years this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); expectedValue = (new Date()).getTime() - (63072000L * 1000); actualValue = extvalue.getDate().getTime(); diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); } finally { endEntityManagementSession.revokeAndDeleteUser(admin, username, CRLReason.unspecified); eeProfSession.removeEndEntityProfile(admin, eepname); certProfSession.removeCertificateProfile(admin, cpname); } }
From source file:org.dogtagpki.server.rest.UserService.java
/** * Adds a certificate to a user/*from w ww .j av a2s.co m*/ * <P> * * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ * ui/admin-protocol-definition.html#user-admin * <P> * * <ul> * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under * users/groups) * </ul> */ @Override public Response addUserCert(String userID, UserCertData userCertData) { if (userCertData == null) throw new BadRequestException("Certificate data is null."); // ensure that any low-level exceptions are reported // to the signed audit log and stored as failures try { if (userID == null) { log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers)); } IUser user = userGroupManager.createUser(userID); String encoded = userCertData.getEncoded(); // no cert is a success if (encoded == null) { auditAddUserCert(userID, userCertData, ILogger.SUCCESS); return createOKResponse(); } // only one cert added per operation X509Certificate cert = null; // Base64 decode cert byte binaryCert[] = Cert.parseCertificate(encoded); try { cert = new X509CertImpl(binaryCert); } catch (CertificateException e) { CMS.debug("UserService: Submitted data is not an X.509 certificate: " + e); // ignore } if (cert == null) { // TODO: Remove this code. Importing PKCS #7 is not supported. // cert chain direction boolean assending = true; // could it be a pkcs7 blob? CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_IS_PK_BLOB")); try { CryptoManager manager = CryptoManager.getInstance(); PKCS7 pkcs7 = new PKCS7(binaryCert); X509Certificate p7certs[] = pkcs7.getCertificates(); if (p7certs.length == 0) { CMS.debug("UserService: PKCS #7 data contains no certificates"); throw new BadRequestException("PKCS #7 data contains no certificates"); } // fix for 370099 - cert ordering can not be assumed // find out the ordering ... // self-signed and alone? take it. otherwise test // the ordering if (p7certs[0].getSubjectDN().toString().equals(p7certs[0].getIssuerDN().toString()) && (p7certs.length == 1)) { cert = p7certs[0]; CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT")); } else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) { cert = p7certs[0]; CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_ACEND_ORD")); } else if (p7certs[1].getIssuerDN().toString().equals(p7certs[0].getSubjectDN().toString())) { assending = false; CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_DESC_ORD")); cert = p7certs[p7certs.length - 1]; } else { // not a chain, or in random order CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_BAD_CHAIN")); throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers)); } CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CHAIN_STORED_DB", String.valueOf(p7certs.length))); int j = 0; int jBegin = 0; int jEnd = 0; if (assending == true) { jBegin = 1; jEnd = p7certs.length; } else { jBegin = 0; jEnd = p7certs.length - 1; } // store the chain into cert db, except for the user cert for (j = jBegin; j < jEnd; j++) { CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN", String.valueOf(j), String.valueOf(p7certs[j].getSubjectDN()))); org.mozilla.jss.crypto.X509Certificate leafCert = manager .importCACertPackage(p7certs[j].getEncoded()); if (leafCert == null) { CMS.debug("UserService: missing leaf certificate"); log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NULL")); } else { CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NON_NULL")); } if (leafCert instanceof InternalCertificate) { ((InternalCertificate) leafCert).setSSLTrust(InternalCertificate.VALID_CA | InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA); } else { log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT", String.valueOf(p7certs[j].getSubjectDN()))); } } /* } catch (CryptoManager.UserCertConflictException e) { // got a "user cert" in the chain, most likely the CA // cert of this instance, which has a private key. Ignore log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", e.toString())); */ } catch (PKIException e) { CMS.debug("UserService: Unable to import user certificate from PKCS #7 data: " + e); log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString())); throw e; } catch (Exception e) { CMS.debug(e); log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString())); throw new PKIException("Unable to import user certificate from PKCS #7 data: " + e.getMessage(), e); } } try { CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_BEFORE_VALIDITY")); cert.checkValidity(); // throw exception if fails user.setX509Certificates(new X509Certificate[] { cert }); userGroupManager.addUserCert(user); auditAddUserCert(userID, userCertData, ILogger.SUCCESS); // read the data back userCertData.setVersion(cert.getVersion()); userCertData.setSerialNumber(new CertId(cert.getSerialNumber())); userCertData.setIssuerDN(cert.getIssuerDN().toString()); userCertData.setSubjectDN(cert.getSubjectDN().toString()); String certID = userCertData.getID(); userCertData = getUserCertData(userID, URLEncoder.encode(certID, "UTF-8")); return createCreatedResponse(userCertData, userCertData.getLink().getHref()); } catch (CertificateExpiredException e) { CMS.debug("UserService: Certificate expired: " + e); log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", String.valueOf(cert.getSubjectDN()))); throw new BadRequestException("Certificate expired: " + e.getMessage(), e); } catch (CertificateNotYetValidException e) { CMS.debug("UserService: Certificate not yet valid: " + e); log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", String.valueOf(cert.getSubjectDN()))); throw new BadRequestException("Certificate not yet valid: " + e.getMessage(), e); } } catch (PKIException e) { CMS.debug("UserService: Unable to import user certificate: " + e); auditAddUserCert(userID, userCertData, ILogger.FAILURE); throw e; } catch (Exception e) { CMS.debug(e); log(ILogger.LL_FAILURE, e.toString()); auditAddUserCert(userID, userCertData, ILogger.FAILURE); throw new PKIException("Unable to import user certificate: " + e.getMessage(), e); } }
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; }//from ww w.ja v a 2 s .c o m 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:com.viettel.hqmc.DAO.FilesDAO.java
public static OCSP.RevocationStatus.CertStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) throws Exception { OCSPReq request = generateOCSPRequest2(issuerCert, peerCert.getSerialNumber()); //This list will sometimes have non ocsp urls as well. List<String> locations = getAIALocations(peerCert); for (String serviceUrl : locations) { SingleResp[] responses;// w w w. j a va 2 s. c om try { ResourceBundle rb = ResourceBundle.getBundle("config"); //String host = rb.getString("ocspUrl"); String BCY = rb.getString("BCY"); String checkBCY = issuerCert.getIssuerDN().toString(); String host; if (BCY.equals(checkBCY)) { host = rb.getString("ocspBcyUrl"); } else { host = getOcspUrl(peerCert); } //String host = "http://ocsp.ca.gov.vn:2560"; OCSPResp ocspResponse = getOCSPResponse(host, request); if (OCSPRespStatus.SUCCESSFUL != ocspResponse.getStatus()) { continue; // Server didn't give the response right. } BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); responses = (basicResponse == null) ? null : basicResponse.getResponses(); //todo use the super exception } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 continue; } if (responses != null && responses.length == 1) { SingleResp resp = responses[0]; OCSP.RevocationStatus.CertStatus status = getRevocationStatus(resp); return status; } } throw new Exception("Cant get Revocation Status from OCSP."); }
From source file:com.viettel.hqmc.DAO.FilesDAO.java
/** * * @return @throws IOException//from ww w. j a va 2 s . c o m */ public String actionSignCARegisterCA() throws IOException { boolean result; String base64Hash = ""; String certSerial = ""; String errorCode = ""; SignPdfFile pdfSig = new SignPdfFile(); try { String rootCert = null, base64Certificate = null; Base64 decoder = new Base64(); String certChain = new String( decoder.decode(getRequest().getParameter("cert").replace("_", "+").getBytes()), "UTF-8"); String[] chain; try { chain = certChain.split(","); rootCert = chain[1]; base64Certificate = chain[0]; } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_001"; result = false; } if (base64Certificate == null) { errorCode = "SI_002"; result = false; } X509Certificate x509Cert = null; X509Certificate x509CertChain = null; try { x509Cert = CertUtils.getX509Cert(base64Certificate); x509CertChain = CertUtils.getX509Cert(rootCert); } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_003"; result = false; } PDFServerClientSignature pdfSCS = new PDFServerClientSignature(); ResourceBundle rb = ResourceBundle.getBundle("config"); String TSA_LINK = rb.getString("tsaUrl"); pdfSCS.setTSA_LINK(TSA_LINK); String checkOcspStr = rb.getString("checkOCSP"); Long checkOCSP = Long.parseLong(checkOcspStr); try { certSerial = x509Cert.getSerialNumber().toString(16); } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_004"; result = false; } CaUserDAOHE ca = new CaUserDAOHE(); if (!ca.checkCaSerial("SerialNumber:[" + certSerial + "]")) { result = true; } else { result = false; } try { if (checkOCSP == 1l) { OCSP.RevocationStatus.CertStatus status = checkRevocationStatus((X509Certificate) x509Cert, (X509Certificate) x509CertChain); if (status != OCSP.RevocationStatus.CertStatus.GOOD) { errorCode = "SI_006"; result = false; } } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_007"; result = false; } } catch (JsonSyntaxException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_014"; result = false; } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_015"; result = false; } finally { } List resultMessage = new ArrayList(); if (result) { CaUser caUserBo = new CaUser(); caUserBo.setCaSerial("SerialNumber:[" + certSerial + "]"); caUserBo.setUserName(getUserLogin()); caUserBo.setStatus(1); caUserBo.setBusinessId(getBusinessId()); getSession().saveOrUpdate(caUserBo); BusinessDAOHE bdhe = new BusinessDAOHE(); Business bus = bdhe.findById(getBusinessId()); bus.setIsCa(1l); getSession().update(bus); HttpServletRequest req = getRequest(); HttpSession session = req.getSession(); session.setAttribute("PDFSignature", pdfSig); resultMessage.add("1"); resultMessage.add("Kim tra thng tin ch k s thnh cng."); resultMessage.add(base64Hash); resultMessage.add(certSerial); } else { resultMessage.add("0"); resultMessage.add("Kim tra thng tin ch k s khng thnh cng " + errorCode); } jsonDataGrid.setItems(resultMessage); return GRID_DATA; }