List of usage examples for java.math BigInteger toString
public String toString(int radix)
From source file:com.cloud.network.NetworkModelImpl.java
@Override public List<String[]> generateVmData(String userData, String serviceOffering, String zoneName, String vmName, long vmId, String publicKey, String password, Boolean isWindows) { final List<String[]> vmData = new ArrayList<String[]>(); if (userData != null) { vmData.add(new String[] { "userdata", "user-data", new String(Base64.decodeBase64(userData), StringUtils.getPreferredCharset()) }); }//from w w w. ja v a 2 s.c om vmData.add(new String[] { "metadata", "service-offering", StringUtils.unicodeEscape(serviceOffering) }); vmData.add(new String[] { "metadata", "availability-zone", StringUtils.unicodeEscape(zoneName) }); vmData.add(new String[] { "metadata", "local-hostname", StringUtils.unicodeEscape(vmName) }); vmData.add(new String[] { "metadata", "instance-id", vmName }); vmData.add(new String[] { "metadata", "vm-id", String.valueOf(vmId) }); vmData.add(new String[] { "metadata", "public-keys", publicKey }); String cloudIdentifier = _configDao.getValue("cloud.identifier"); if (cloudIdentifier == null) { cloudIdentifier = ""; } else { cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}"; } vmData.add(new String[] { "metadata", "cloud-identifier", cloudIdentifier }); if (password != null && !password.isEmpty() && !password.equals("saved_password")) { // Here we are calculating MD5 checksum to reduce the over head of calculating MD5 checksum // in windows VM in password reset script. if (isWindows) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { s_logger.error("Unexpected exception " + e.getMessage(), e); throw new CloudRuntimeException("Unable to get MD5 MessageDigest", e); } md5.reset(); md5.update(password.getBytes(StringUtils.getPreferredCharset())); byte[] digest = md5.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashtext = bigInt.toString(16); vmData.add(new String[] { "password", "vm-password-md5checksum", hashtext }); } vmData.add(new String[] { "password", "vm-password", password }); } return vmData; }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** @return a list of trusted signers or CAs */ @Deprecated //This method is only used for upgrading to version 6 private List<InternalKeyBindingTrustEntry> getOcspKeyBindingTrustDefaults() { // Import certificates used to verify OCSP request signatures and add these to each OcspKeyBinding's trust-list // ocsp.signtrustdir=signtrustdir // ocsp.signtrustvalidtime should be ignored final List<InternalKeyBindingTrustEntry> trustedCertificateReferences = new ArrayList<InternalKeyBindingTrustEntry>(); if (OcspConfiguration.getEnforceRequestSigning() && OcspConfiguration.getRestrictSignatures()) { // Import certificates and configure Issuer+serialnumber in trustlist for each final String dirName = OcspConfiguration.getSignTrustDir(); if (dirName != null) { final File directory = new File(dirName); if (directory.isDirectory()) { for (final File file : directory.listFiles()) { try { final List<Certificate> chain = CertTools.getCertsFromPEM(new FileInputStream(file)); if (!chain.isEmpty()) { final String issuerDn = CertTools.getIssuerDN(chain.get(0)); final String subjectDn = CertTools.getSubjectDN(chain.get(0)); if (OcspConfiguration .getRestrictSignaturesByMethod() == OcspConfiguration.RESTRICTONSIGNER) { final int caId = issuerDn.hashCode(); final BigInteger serialNumber = CertTools.getSerialNumber(chain.get(0)); if (!caSession.existsCa(caId)) { log.warn("Trusted certificate with serialNumber " + serialNumber.toString(16) + " is issued by an unknown CA with subject '" + issuerDn + "'. You should import this CA certificate as en external CA to make it known to the system."); }/* www . j a v a 2 s . com*/ trustedCertificateReferences .add(new InternalKeyBindingTrustEntry(caId, serialNumber)); } else { final int caId = subjectDn.hashCode(); if (!caSession.existsCa(caId)) { log.warn("Trusted CA certificate with with subject '" + subjectDn + "' should be imported as en external CA to make it known to the system."); } trustedCertificateReferences.add(new InternalKeyBindingTrustEntry(caId, null)); } } } catch (CertificateException e) { log.warn(e.getMessage()); } catch (FileNotFoundException e) { log.warn(e.getMessage()); } } } } } return trustedCertificateReferences; }
From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionBean.java
@Override public void revokeCert(AuthenticationToken admin, BigInteger certserno, Date revocationdate, String issuerdn, int reason, boolean checkDate) throws AuthorizationDeniedException, FinderException, ApprovalException, WaitingForApprovalException, RevokeBackDateNotAllowedForProfileException, AlreadyRevokedException { if (log.isTraceEnabled()) { log.trace(">revokeCert(" + certserno.toString(16) + ", IssuerDN: " + issuerdn + ")"); }//from w ww . j a va 2s .co m // Check that the admin has revocation rights. if (!authorizationSession.isAuthorizedNoLogging(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) { String msg = intres.getLocalizedMessage("ra.errorauthrevoke"); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, EjbcaModuleTypes.RA, ServiceTypes.CORE, admin.toString(), null, certserno.toString(16).toUpperCase(), null, details); throw new AuthorizationDeniedException(msg); } // To be fully backwards compatible we just use the first fingerprint found.. final CertificateInfo info = certificateStoreSession.findFirstCertificateInfo(issuerdn, certserno); if (info == null) { final String msg = intres.getLocalizedMessage("ra.errorfindentitycert", issuerdn, certserno.toString(16)); log.info(msg); throw new FinderException(msg); } final int caid = info.getIssuerDN().hashCode(); final String username = info.getUsername(); assertAuthorizedToCA(admin, caid); int certificateProfileId = info.getCertificateProfileId(); String userDataDN = info.getSubjectDN(); final CertReqHistory certReqHistory = certreqHistorySession.retrieveCertReqHistory(certserno, issuerdn); UserData data = null; if (certReqHistory == null || XkmsConfiguration.getEnabled()) { // We could use userdata later, so try to find it data = UserData.findByUsername(entityManager, username); } int endEntityProfileId = -1; if (certReqHistory != null) { // Get the EEP that was used in the original issuance, if we can find it endEntityProfileId = certReqHistory.getEndEntityInformation().getEndEntityProfileId(); // Republish with the same user DN that was used in the original publication, if we can find it userDataDN = certReqHistory.getEndEntityInformation().getCertificateDN(); // If for some reason the certificate profile id was not set in the certificate data, try to get it from the certreq history if (certificateProfileId == CertificateProfileConstants.CERTPROFILE_NO_PROFILE) { certificateProfileId = certReqHistory.getEndEntityInformation().getCertificateProfileId(); } } else if (data != null) { // Get the EEP that is currently used as a fallback, if we can find it endEntityProfileId = data.getEndEntityProfileId(); // Republish with the same user DN that is currently used as a fallback, if we can find it userDataDN = data.toEndEntityInformation().getCertificateDN(); // If for some reason the certificate profile id was not set in the certificate data, try to get it from current userdata if (certificateProfileId == CertificateProfileConstants.CERTPROFILE_NO_PROFILE) { certificateProfileId = data.getCertificateProfileId(); } } if (endEntityProfileId != -1) { // We can only perform this check if we have a trail of what eep was used.. if (getGlobalConfiguration().getEnableEndEntityProfileLimitations()) { assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.REVOKE_END_ENTITY, caid); } } // Check that unrevocation is not done on anything that can not be unrevoked if (reason == RevokedCertInfo.NOT_REVOKED || reason == RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { if (info.getRevocationReason() != RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD) { final String msg = intres.getLocalizedMessage("ra.errorunrevokenotonhold", issuerdn, certserno.toString(16)); log.info(msg); throw new AlreadyRevokedException(msg); } } else { if (info.getRevocationReason() != RevokedCertInfo.NOT_REVOKED && // it should be possible to revoke a certificate on hold for good. info.getRevocationReason() != RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD && // a valid certificate could have reason "REVOCATION_REASON_REMOVEFROMCRL" if it has been revoked in the past. info.getRevocationReason() != RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { final String msg = intres.getLocalizedMessage("ra.errorrevocationexists", issuerdn, certserno.toString(16)); log.info(msg); throw new AlreadyRevokedException(msg); } } if (endEntityProfileId != -1 && certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE) { // We can only perform this check if we have a trail of what eep and cp was used.. // Check if approvals is required. final int numOfReqApprovals = getNumOfApprovalRequired(CAInfo.REQ_APPROVAL_REVOCATION, caid, certificateProfileId); if (numOfReqApprovals > 0) { final RevocationApprovalRequest ar = new RevocationApprovalRequest(certserno, issuerdn, username, reason, admin, numOfReqApprovals, caid, endEntityProfileId); if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_REVOKECERT)) { approvalSession.addApprovalRequest(admin, ar); throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalrevoke")); } } } // Finally find the publishers for the certificate profileId that we found Collection<Integer> publishers = new ArrayList<Integer>(0); final CertificateProfile certificateProfile = certificateProfileSession .getCertificateProfile(certificateProfileId); if (certificateProfile != null) { publishers = certificateProfile.getPublisherList(); if (publishers == null || publishers.size() == 0) { if (log.isDebugEnabled()) { log.debug("No publishers defined for certificate with serial #" + certserno.toString(16) + " issued by " + issuerdn); } } } else { log.warn("No certificate profile for certificate with serial #" + certserno.toString(16) + " issued by " + issuerdn); } if (checkDate && revocationdate != null && (certificateProfile == null || !certificateProfile.getAllowBackdatedRevocation())) { final String profileName = this.certificateProfileSession .getCertificateProfileName(certificateProfileId); final String m = intres.getLocalizedMessage("ra.norevokebackdate", profileName, certserno.toString(16), issuerdn); throw new RevokeBackDateNotAllowedForProfileException(m); } // Revoke certificate in database and all publishers try { this.revocationSession.revokeCertificate(admin, issuerdn, certserno, revocationdate != null ? revocationdate : new Date(), publishers, reason, userDataDN); } catch (CertificateRevokeException e) { final String msg = intres.getLocalizedMessage("ra.errorfindentitycert", issuerdn, certserno.toString(16)); log.info(msg); throw new FinderException(msg); } if (XkmsConfiguration.getEnabled() && data != null) { // Reset the revocation code identifier used in XKMS final ExtendedInformation inf = data.getExtendedInformation(); if (inf != null && inf.getRevocationCodeIdentifier() != null) { inf.setRevocationCodeIdentifier(null); data.setExtendedInformation(inf); } } if (log.isTraceEnabled()) { log.trace("<revokeCert()"); } }
From source file:org.ejbca.core.ejb.ra.UserAdminSessionBean.java
@Override public void revokeCert(Admin admin, BigInteger certserno, Date revocationdate, String issuerdn, int reason, boolean checkDate) throws AuthorizationDeniedException, FinderException, WaitingForApprovalException, RevokeBackDateNotAllowedForProfileException, AlreadyRevokedException, ApprovalException { if (log.isTraceEnabled()) { log.trace(">revokeCert(" + certserno.toString(16) + ", IssuerDN: " + issuerdn + ")"); }/* www. java 2 s . c o m*/ // Check that the admin has revocation rights. if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) { Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null); } // To be fully backwards compatible we just use the first fingerprint found.. final CertificateInfo info = certificateStoreSession.findFirstCertificateInfo(issuerdn, certserno); if (info == null) { final String msg = intres.getLocalizedMessage("ra.errorfindentitycert", issuerdn, certserno.toString(16)); logSession.log(admin, LogConstants.INTERNALCAID, LogConstants.MODULE_RA, new Date(), null, null, LogConstants.EVENT_INFO_REVOKEDENDENTITY, msg); throw new FinderException(msg); } final int caid = info.getIssuerDN().hashCode(); final String username = info.getUsername(); assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_ERROR_REVOKEDENDENTITY); int certificateProfileId = info.getCertificateProfileId(); String userDataDN = info.getSubjectDN(); final CertReqHistory certReqHistory = certificateStoreSession.getCertReqHistory(admin, certserno, issuerdn); UserData data = null; if (certReqHistory == null || XkmsConfiguration.getEnabled()) { // We could use userdata later, so try to find it data = UserData.findByUsername(entityManager, username); } int endEntityProfileId = -1; if (certReqHistory != null) { // Get the EEP that was used in the original issuance, if we can find it endEntityProfileId = certReqHistory.getUserDataVO().getEndEntityProfileId(); // Republish with the same user DN that was used in the original publication, if we can find it userDataDN = certReqHistory.getUserDataVO().getCertificateDN(); // If for some reason the certificate profile id was not set in the certificate data, try to get it from the certreq history if (certificateProfileId == SecConst.CERTPROFILE_NO_PROFILE) { certificateProfileId = certReqHistory.getUserDataVO().getCertificateProfileId(); } } else if (data != null) { // Get the EEP that is currently used as a fallback, if we can find it endEntityProfileId = data.getEndEntityProfileId(); // Republish with the same user DN that is currently used as a fallback, if we can find it userDataDN = data.toUserDataVO().getCertificateDN(); // If for some reason the certificate profile id was not set in the certificate data, try to get it from current userdata if (certificateProfileId == SecConst.CERTPROFILE_NO_PROFILE) { certificateProfileId = data.getCertificateProfileId(); } } if (endEntityProfileId != -1) { // We can only perform this check if we have a trail of what eep was used.. if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) { assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.REVOKE_RIGHTS, caid, username, LogConstants.EVENT_ERROR_REVOKEDENDENTITY); } } // Check that unrevocation is not done on anything that can not be unrevoked if (reason == RevokedCertInfo.NOT_REVOKED || reason == RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { if (info.getRevocationReason() != RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD) { final String msg = intres.getLocalizedMessage("ra.errorunrevokenotonhold", issuerdn, certserno.toString(16)); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_INFO_REVOKEDENDENTITY, msg); throw new AlreadyRevokedException(msg); } } else { if (info.getRevocationReason() != RevokedCertInfo.NOT_REVOKED && // a valid certificate could have reason "REVOCATION_REASON_REMOVEFROMCRL" if it has been revoked in the past. info.getRevocationReason() != RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { final String msg = intres.getLocalizedMessage("ra.errorrevocationexists"); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_INFO_REVOKEDENDENTITY, msg); throw new AlreadyRevokedException(msg); } } if (endEntityProfileId != -1 && certificateProfileId != SecConst.CERTPROFILE_NO_PROFILE) { // We can only perform this check if we have a trail of what eep and cp was used.. // Check if approvals is required. final int numOfReqApprovals = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_REVOCATION, caid, certificateProfileId); if (numOfReqApprovals > 0) { final RevocationApprovalRequest ar = new RevocationApprovalRequest(certserno, issuerdn, username, reason, admin, numOfReqApprovals, caid, endEntityProfileId); if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_REVOKECERT)) { approvalSession.addApprovalRequest(admin, ar, getGlobalConfiguration(admin)); throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalrevoke")); } } } // Finally find the publishers for the certificate profileId that we found Collection<Integer> publishers = new ArrayList<Integer>(0); final CertificateProfile certificateProfile = certificateProfileSession.getCertificateProfile(admin, certificateProfileId); if (certificateProfile != null) { publishers = certificateProfile.getPublisherList(); if (publishers == null || publishers.size() == 0) { if (log.isDebugEnabled()) { log.debug("No publishers defined for certificate with serial #" + certserno.toString(16) + " issued by " + issuerdn); } } } else { log.warn("No certificate profile for certificate with serial #" + certserno.toString(16) + " issued by " + issuerdn); } if (checkDate && revocationdate != null && (certificateProfile == null || !certificateProfile.getAllowBackdatedRevocation())) { final String profileName = this.certificateProfileSession.getCertificateProfileName(admin, certificateProfileId); final String m = intres.getLocalizedMessage("ra.norevokebackdate", profileName, certserno.toString(16), issuerdn); throw new RevokeBackDateNotAllowedForProfileException(m); } // Revoke certificate in database and all publishers this.certificateStoreSession.setRevokeStatus(admin, issuerdn, certserno, revocationdate != null ? revocationdate : new Date(), publishers, reason, userDataDN); if (XkmsConfiguration.getEnabled() && data != null) { // Reset the revocation code identifier used in XKMS final ExtendedInformation inf = data.getExtendedInformation(); if (inf != null && inf.getRevocationCodeIdentifier() != null) { inf.setRevocationCodeIdentifier(null); data.setExtendedInformation(inf); } } if (log.isTraceEnabled()) { log.trace("<revokeCert()"); } }
From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionBean.java
@TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override/*from www . ja v a 2 s . com*/ public boolean checkIfCertificateBelongToUser(BigInteger certificatesnr, String issuerdn) { if (!WebConfiguration.getRequireAdminCertificateInDatabase()) { if (log.isTraceEnabled()) { log.trace("<checkIfCertificateBelongToUser Configured to ignore if cert belongs to user."); } return true; } final String username = certificateStoreSession.findUsernameByCertSerno(certificatesnr, issuerdn); if (username != null) { if (UserData.findByUsername(entityManager, username) == null) { final String msg = intres.getLocalizedMessage("ra.errorcertnouser", issuerdn, certificatesnr.toString(16)); log.info(msg); return false; } else { return true; } } else { return false; } }
From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java
License:asdf
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void updateLimitedCertificateDataStatus(final AuthenticationToken admin, final int caId, final String issuerDn, final BigInteger serialNumber, final Date revocationDate, final int reasonCode, final String caFingerprint) throws AuthorizationDeniedException { if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.CAACCESS.resource() + caId)) { final String msg = INTRES.getLocalizedMessage("caadmin.notauthorizedtoca", admin.toString(), caId); throw new AuthorizationDeniedException(msg); }//from w w w . j av a 2 s.c o m final CertificateInfo certificateInfo = findFirstCertificateInfo(issuerDn, serialNumber); final String limitedFingerprint = getLimitedCertificateDataFingerprint(issuerDn, serialNumber); final CertificateData limitedCertificateData = createLimitedCertificateData(admin, limitedFingerprint, issuerDn, serialNumber, revocationDate, reasonCode, caFingerprint); if (certificateInfo == null) { if (reasonCode == RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { deleteLimitedCertificateData(limitedFingerprint); } else { // Create a limited entry log.info("Adding limited CertificateData entry with fingerprint=" + limitedFingerprint + ", serialNumber=" + serialNumber.toString(16).toUpperCase() + ", issuerDn='" + issuerDn + "'"); entityManager.persist(limitedCertificateData); } } else if (limitedFingerprint.equals(certificateInfo.getFingerprint())) { if (reasonCode == RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL) { deleteLimitedCertificateData(limitedFingerprint); } else { if (certificateInfo.getStatus() != limitedCertificateData.getStatus() || certificateInfo.getRevocationDate().getTime() != limitedCertificateData .getRevocationDate() || certificateInfo.getRevocationReason() != limitedCertificateData.getRevocationReason()) { // Update the limited entry log.info("Updating limited CertificateData entry with fingerprint=" + limitedFingerprint + ", serialNumber=" + serialNumber.toString(16).toUpperCase() + ", issuerDn='" + issuerDn + "'"); entityManager.merge(limitedCertificateData); } else { if (log.isDebugEnabled()) { log.debug("Limited CertificateData entry with fingerprint=" + limitedFingerprint + ", serialNumber=" + serialNumber.toString(16).toUpperCase() + ", issuerDn='" + issuerDn + "' was already up to date."); } } } } else { // Refuse to update a normal entry with this method throw new UnsupportedOperationException( "Only limited certificate entries can be updated using this method."); } }
From source file:org.accada.reader.rprm.core.Source.java
private String getTagId(String tagIdHex, int filter, int taglength, int companyprefixlength, LevelTypeList outputLevel) {/*from w w w . ja v a 2 s . c o m*/ BigInteger big = new BigInteger(tagIdHex, 16); String binaryTagId = big.toString(2); while (binaryTagId.length() < taglength) { binaryTagId = "0" + binaryTagId; } Map<String, String> params = new HashMap<String, String>(); params.put("filter", new Integer(filter).toString()); params.put("taglength", new Integer(taglength).toString()); params.put("companyprefixlength", new Integer(companyprefixlength).toString()); LOG.debug("Convert TagId '" + binaryTagId + "' to " + outputLevel); String result; try { TDTEngine engine = new TDTEngine("./props"); result = engine.convert(binaryTagId, params, outputLevel); } catch (Exception e) { result = binaryTagId; } LOG.debug(outputLevel + ": " + result); return result; }
From source file:org.ejbca.ui.web.protocol.OCSPServletBase.java
/** Performs service of the actual OCSP request, which is contained in reqBytes. * // w ww. j a v a 2 s . com * @param reqBytes the binary OCSP request bytes. This parameter must already have been checked for max or min size. */ public void serviceOCSP(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (m_log.isTraceEnabled()) { m_log.trace(">service()"); } final int localTransactionID; synchronized (this) { this.mTransactionID += 1; localTransactionID = this.mTransactionID; } final IPatternLogger transactionLogger; final IPatternLogger auditLogger; final Date startTime = new Date(); if (this.mDoTransactionLog) { transactionLogger = this.transactionLogger.getPatternLogger(); } else { transactionLogger = new DummyPatternLogger(); // Ignores everything } if (this.mDoAuditLog) { auditLogger = this.auditLogger.getPatternLogger(); } else { auditLogger = new DummyPatternLogger(); // Ignores everything } final String remoteAddress = request.getRemoteAddr(); auditLogger.paramPut(IAuditLogger.OCSPREQUEST, ""); // No request bytes yet auditLogger.paramPut(IPatternLogger.LOG_ID, new Integer(localTransactionID)); auditLogger.paramPut(IPatternLogger.SESSION_ID, this.m_SessionID); auditLogger.paramPut(IOCSPLogger.CLIENT_IP, remoteAddress); transactionLogger.paramPut(IPatternLogger.LOG_ID, new Integer(localTransactionID)); transactionLogger.paramPut(IPatternLogger.SESSION_ID, this.m_SessionID); transactionLogger.paramPut(IOCSPLogger.CLIENT_IP, remoteAddress); try { // Read configuration values affecting the response, these can be dynamically updated from properties files in file system // Read default values here for each request since may take a millisecond to read the value // These values can be changed depending on if there are different configurations for different certificate profiles // In that case it is updated once we have read the certificate status of the certificate searched for. long maxAge = OcspConfiguration.getMaxAge(SecConst.CERTPROFILE_NO_PROFILE); long nextUpdate = OcspConfiguration.getUntilNextUpdate(SecConst.CERTPROFILE_NO_PROFILE); OCSPResp ocspresp = null; OCSPRespGenerator res = new OCSPRespGenerator(); X509Certificate cacert = null; // CA-certificate used to sign response try { byte[] reqBytes = checkAndGetRequestBytes(request); // Start logging process time after we have received the request transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IAuditLogger.OCSPREQUEST, new String(Hex.encode(reqBytes))); OCSPReq req = null; try { req = new OCSPReq(reqBytes); } catch (Exception e) { // When not being able to parse the request, we want to send a MalformedRequest back throw new MalformedRequestException(e); } if (req.getRequestorName() == null) { m_log.debug("Requestorname is null"); } else { if (m_log.isDebugEnabled()) { m_log.debug("Requestorname is: " + req.getRequestorName().toString()); } transactionLogger.paramPut(ITransactionLogger.REQ_NAME, req.getRequestorName().toString()); } // Make sure our signature keys are updated loadPrivateKeys(this.data.m_adm, null); /** * check the signature if contained in request. * if the request does not contain a signature * and the servlet is configured in the way * the a signature is required we send back * 'sigRequired' response. */ if (m_log.isDebugEnabled()) { m_log.debug("Incoming OCSP request is signed : " + req.isSigned()); } if (req.isSigned()) { X509Certificate signercert = OCSPUtil.checkRequestSignature(request.getRemoteAddr(), req, this.data.m_caCertCache); String signercertIssuerName = CertTools.getIssuerDN(signercert); BigInteger signercertSerNo = CertTools.getSerialNumber(signercert); String signercertSubjectName = CertTools.getSubjectDN(signercert); transactionLogger.paramPut(ITransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName); transactionLogger.paramPut(ITransactionLogger.SIGN_SERIAL_NO, signercert.getSerialNumber().toByteArray()); transactionLogger.paramPut(ITransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName); transactionLogger.paramPut(IPatternLogger.REPLY_TIME, ITransactionLogger.REPLY_TIME); if (OcspConfiguration.getEnforceRequestSigning()) { // If it verifies OK, check if it is revoked final CertificateStatus status = this.data.certificateStoreSession.getStatus( CertTools.getIssuerDN(signercert), CertTools.getSerialNumber(signercert)); // If rci == null it means the certificate does not exist in database, we then treat it as ok, // because it may be so that only revoked certificates is in the (external) OCSP database. if (status.equals(CertificateStatus.REVOKED)) { String serno = signercertSerNo.toString(16); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.revoked", signercertSubjectName, signercertIssuerName, serno); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } if (m_reqRestrictSignatures) { loadTrustDir(); if (m_reqRestrictMethod == OcspConfiguration.RESTRICTONSIGNER) { if (!OCSPUtil.checkCertInList(signercert, mTrustedReqSigSigners)) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } else if (m_reqRestrictMethod == OcspConfiguration.RESTRICTONISSUER) { X509Certificate signerca = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(signercertIssuerName)); if ((signerca == null) || (!OCSPUtil.checkCertInList(signerca, mTrustedReqSigIssuers))) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } else { throw new Exception("m_reqRestrictMethod=" + m_reqRestrictMethod); // there must be an internal error. We do not want to send a response, just to be safe. } } } } else { if (OcspConfiguration.getEnforceRequestSigning()) { // Signature required throw new SignRequestException("Signature required"); } } // Get the certificate status requests that are inside this OCSP req Req[] requests = req.getRequestList(); transactionLogger.paramPut(ITransactionLogger.NUM_CERT_ID, requests.length); if (requests.length <= 0) { String infoMsg = intres.getLocalizedMessage("ocsp.errornoreqentities"); m_log.info(infoMsg); { // All this just so we can create an error response cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); } throw new MalformedRequestException(infoMsg); } int maxRequests = 100; if (requests.length > maxRequests) { String infoMsg = intres.getLocalizedMessage("ocsp.errortoomanyreqentities", maxRequests); m_log.info(infoMsg); { // All this just so we can create an error response cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); } throw new MalformedRequestException(infoMsg); } if (m_log.isDebugEnabled()) { m_log.debug("The OCSP request contains " + requests.length + " simpleRequests."); } // Add standard response extensions Hashtable responseExtensions = OCSPUtil.getStandardResponseExtensions(req); transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); // Look over the status requests ArrayList responseList = new ArrayList(); for (int i = 0; i < requests.length; i++) { CertificateID certId = requests[i].getCertID(); // now some Logging transactionLogger.paramPut(ITransactionLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); transactionLogger.paramPut(ITransactionLogger.DIGEST_ALGOR, certId.getHashAlgOID()); //todo, find text version of this or find out if it should be something else transactionLogger.paramPut(ITransactionLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash()); transactionLogger.paramPut(ITransactionLogger.ISSUER_KEY, certId.getIssuerKeyHash()); auditLogger.paramPut(IAuditLogger.ISSUER_KEY, certId.getIssuerKeyHash()); auditLogger.paramPut(IAuditLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); auditLogger.paramPut(IAuditLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash()); byte[] hashbytes = certId.getIssuerNameHash(); String hash = null; if (hashbytes != null) { hash = new String(Hex.encode(hashbytes)); } String infoMsg = intres.getLocalizedMessage("ocsp.inforeceivedrequest", certId.getSerialNumber().toString(16), hash, request.getRemoteAddr()); m_log.info(infoMsg); boolean unknownCA = false; // if the certId was issued by an unknown CA // The algorithm here: // We will sign the response with the CA that issued the first // certificate(certId) in the request. If the issuing CA is not available // on this server, we sign the response with the default responderId (from params in web.xml). // We have to look up the ca-certificate for each certId in the request though, as we will check // for revocation on the ca-cert as well when checking for revocation on the certId. cacert = this.data.m_caCertCache.findByOcspHash(certId); // Get the issuer of certId if (cacert == null) { // We could not find certificate for this request so get certificate for default responder cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); unknownCA = true; } if (cacert == null) { String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacert", new String(Hex.encode(certId.getIssuerNameHash())), this.data.m_defaultResponderId); m_log.error(errMsg); continue; } if (unknownCA == true) { String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacertusedefault", new String(Hex.encode(certId.getIssuerNameHash()))); m_log.info(errMsg); // If we can not find the CA, answer UnknowStatus responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate)); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_UNKNOWN); transactionLogger.writeln(); continue; } else { transactionLogger.paramPut(ITransactionLogger.ISSUER_NAME_DN, cacert.getSubjectDN().getName()); } /* * Implement logic according to * chapter 2.7 in RFC2560 * * 2.7 CA Key Compromise * If an OCSP responder knows that a particular CA's private key has * been compromised, it MAY return the revoked state for all * certificates issued by that CA. */ final org.bouncycastle.ocsp.CertificateStatus certStatus; transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); // it seems to be correct // Check if the cacert (or the default responderid) is revoked final CertificateStatus cacertStatus = this.data.certificateStoreSession .getStatus(CertTools.getIssuerDN(cacert), CertTools.getSerialNumber(cacert)); if (!cacertStatus.equals(CertificateStatus.REVOKED)) { // Check if cert is revoked final CertificateStatus status = this.data.certificateStoreSession .getStatus(cacert.getSubjectDN().getName(), certId.getSerialNumber()); // If we have different maxAge and untilNextUpdate for different certificate profiles, we have to fetch these // values now that we have fetched the certificate status, that includes certificate profile. nextUpdate = OcspConfiguration.getUntilNextUpdate(status.certificateProfileId); maxAge = OcspConfiguration.getMaxAge(status.certificateProfileId); if (m_log.isDebugEnabled()) { m_log.debug("Set nextUpdate=" + nextUpdate + ", and maxAge=" + maxAge + " for certificateProfileId=" + status.certificateProfileId); } final String sStatus; if (status.equals(CertificateStatus.NOT_AVAILABLE)) { // No revocation info available for this cert, handle it if (m_log.isDebugEnabled()) { m_log.debug("Unable to find revocation information for certificate with serial '" + certId.getSerialNumber().toString(16) + "'" + " from issuer '" + cacert.getSubjectDN().getName() + "'"); } // If we do not treat non existing certificates as good // OR // we don't actually handle requests for the CA issuing the certificate asked about // then we return unknown if (!nonExistingIsGood(request.getRequestURL()) || this.data.m_caCertCache.findByOcspHash(certId) == null) { sStatus = "unknown"; certStatus = new UnknownStatus(); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_UNKNOWN); } else { sStatus = "good"; certStatus = null; // null means "good" in OCSP transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); } } else if (status.equals(CertificateStatus.REVOKED)) { // Revocation info available for this cert, handle it sStatus = "revoked"; certStatus = new RevokedStatus( new RevokedInfo(new DERGeneralizedTime(status.revocationDate), new CRLReason(status.revocationReason))); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_REVOKED); //1 = revoked } else { sStatus = "good"; certStatus = null; transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); } infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", sStatus, certId.getSerialNumber().toString(16), cacert.getSubjectDN().getName()); m_log.info(infoMsg); responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate)); transactionLogger.writeln(); } else { certStatus = new RevokedStatus( new RevokedInfo(new DERGeneralizedTime(cacertStatus.revocationDate), new CRLReason(cacertStatus.revocationReason))); infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", "revoked", certId.getSerialNumber().toString(16), cacert.getSubjectDN().getName()); m_log.info(infoMsg); responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate)); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_REVOKED); transactionLogger.writeln(); } // Look for extension OIDs Iterator iter = m_extensionOids.iterator(); while (iter.hasNext()) { String oidstr = (String) iter.next(); DERObjectIdentifier oid = new DERObjectIdentifier(oidstr); X509Extensions reqexts = req.getRequestExtensions(); if (reqexts != null) { X509Extension ext = reqexts.getExtension(oid); if (null != ext) { // We found an extension, call the extenstion class if (m_log.isDebugEnabled()) { m_log.debug("Found OCSP extension oid: " + oidstr); } IOCSPExtension extObj = (IOCSPExtension) m_extensionMap.get(oidstr); if (extObj != null) { // Find the certificate from the certId X509Certificate cert = null; cert = (X509Certificate) this.data.certificateStoreSession .findCertificateByIssuerAndSerno(this.data.m_adm, cacert.getSubjectDN().getName(), certId.getSerialNumber()); if (cert != null) { // Call the OCSP extension Hashtable retext = extObj.process(request, cert, certStatus); if (retext != null) { // Add the returned X509Extensions to the responseExtension we will add to the basic OCSP response responseExtensions.putAll(retext); } else { String errMsg = intres.getLocalizedMessage("ocsp.errorprocessextension", extObj.getClass().getName(), new Integer(extObj.getLastErrorCode())); m_log.error(errMsg); } } } } } } } // end of huge for loop if (cacert != null) { // Add responseExtensions X509Extensions exts = new X509Extensions(responseExtensions); // generate the signed response object BasicOCSPResp basicresp = signOCSPResponse(req, responseList, exts, cacert); ocspresp = res.generate(OCSPRespGenerator.SUCCESSFUL, basicresp); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); } else { // Only unknown CAs in requests and no default reponders cert String errMsg = intres.getLocalizedMessage("ocsp.errornocacreateresp"); m_log.error(errMsg); throw new ServletException(errMsg); } } catch (MalformedRequestException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); if (m_log.isDebugEnabled()) { m_log.debug(errMsg, e); } ocspresp = res.generate(OCSPRespGenerator.MALFORMED_REQUEST, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.MALFORMED_REQUEST); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.MALFORMED_REQUEST); } catch (SignRequestException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); // No need to log the full exception here ocspresp = res.generate(OCSPRespGenerator.SIG_REQUIRED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SIG_REQUIRED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SIG_REQUIRED); } catch (SignRequestSignatureException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); // No need to log the full exception here ocspresp = res.generate(OCSPRespGenerator.UNAUTHORIZED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); } catch (InvalidKeyException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg, e); ocspresp = res.generate(OCSPRespGenerator.UNAUTHORIZED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); } catch (Throwable e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.error(errMsg, e); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.INTERNAL_ERROR); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.INTERNAL_ERROR); } byte[] respBytes = ocspresp.getEncoded(); auditLogger.paramPut(IAuditLogger.OCSPRESPONSE, new String(Hex.encode(respBytes))); auditLogger.writeln(); auditLogger.flush(); transactionLogger.flush(); if (mDoSaferLogging) { // See if the Errorhandler has found any problems if (hasErrorHandlerFailedSince(startTime)) { m_log.info("ProbableErrorhandler reported error, cannot answer request"); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. respBytes = ocspresp.getEncoded(); } // See if the Appender has reported any problems if (!canlog) { m_log.info("SaferDailyRollingFileAppender reported error, cannot answer request"); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. respBytes = ocspresp.getEncoded(); } } response.setContentType("application/ocsp-response"); //response.setHeader("Content-transfer-encoding", "binary"); response.setContentLength(respBytes.length); addRfc5019CacheHeaders(request, response, ocspresp, maxAge); response.getOutputStream().write(respBytes); response.getOutputStream().flush(); } catch (OCSPException e) { String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.error(errMsg, e); throw new ServletException(e); } catch (Exception e) { m_log.error("", e); transactionLogger.flush(); auditLogger.flush(); } if (m_log.isTraceEnabled()) { m_log.trace("<service()"); } }
From source file:com.peterbochs.instrument.InstrumentPanel.java
private void loadInformation(boolean sort, String str) { String address[] = str.split(":"); HashSet<BigInteger> c = new HashSet<BigInteger>(); for (int x = 0; x < address.length; x++) { try {// ww w.j a v a2s . c om c.add(CommonLib.string2BigInteger(address[x])); } catch (Exception ex) { } } Vector<BigInteger> v = new Vector<BigInteger>(); Iterator<BigInteger> it = c.iterator(); while (it.hasNext()) { BigInteger element = it.next(); v.add(element); } if (sort) { Collections.sort(v); } jTextArea1.setText(""); Iterator<BigInteger> it2 = v.iterator(); while (it2.hasNext()) { BigInteger element = it2.next(); jTextArea1.setText(jTextArea1.getText() + "\n0x" + element.toString(16)); } }
From source file:org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource.java
private Answer execute(ComputeChecksumCommand cmd) { String relativeTemplatePath = cmd.getTemplatePath(); DataStoreTO store = cmd.getStore();//from w w w . j a v a 2 s .c om if (!(store instanceof NfsTO)) { return new Answer(cmd, false, "can't handle non nfs data store"); } NfsTO nfsStore = (NfsTO) store; String parent = getRootDir(nfsStore.getUrl(), _nfsVersion); if (relativeTemplatePath.startsWith(File.separator)) { relativeTemplatePath = relativeTemplatePath.substring(1); } if (!parent.endsWith(File.separator)) { parent += File.separator; } String absoluteTemplatePath = parent + relativeTemplatePath; MessageDigest digest; String checksum = null; File f = new File(absoluteTemplatePath); InputStream is = null; byte[] buffer = new byte[8192]; int read = 0; if (s_logger.isDebugEnabled()) { s_logger.debug("parent path " + parent + " relative template path " + relativeTemplatePath); } try { digest = MessageDigest.getInstance("MD5"); is = new FileInputStream(f); while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); checksum = bigInt.toString(16); if (s_logger.isDebugEnabled()) { s_logger.debug( "Successfully calculated checksum for file " + absoluteTemplatePath + " - " + checksum); } } catch (IOException e) { String logMsg = "Unable to process file for MD5 - " + absoluteTemplatePath; s_logger.error(logMsg); return new Answer(cmd, false, checksum); } catch (NoSuchAlgorithmException e) { return new Answer(cmd, false, checksum); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Could not close the file " + absoluteTemplatePath); } return new Answer(cmd, false, checksum); } } return new Answer(cmd, true, checksum); }