Example usage for java.math BigInteger equals

List of usage examples for java.math BigInteger equals

Introduction

In this page you can find the example usage for java.math BigInteger equals.

Prototype

public boolean equals(Object x) 

Source Link

Document

Compares this BigInteger with the specified Object for equality.

Usage

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

private ArrayList<JSONRPCTransactionAmount> getAssetTransactionAmounts(Wallet wallet, Transaction tx,
        boolean excludeBTCFee, boolean absoluteBTCFee) {
    if (wallet == null || tx == null)
        return null;

    Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx);
    Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx);

    //   System.out.println(">>>> tx = " + tx.getHashAsString());
    //   System.out.println(">>>>     receive map = " +  receiveMap);
    //   System.out.println(">>>>     send map = " +  sendMap);

    //Map<String, String> nameAmountMap = new TreeMap<>();
    ArrayList<JSONRPCTransactionAmount> resultList = new ArrayList<>();

    boolean isSentByMe = tx.sent(wallet);
    Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap;

    //   Integer assetID = null;
    BigInteger netAmount = null;//from w  w w . j a  v  a 2s.  c  om

    //   for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) {
    for (Integer assetID : loopMap.keySet()) {
        //       assetID = entry.getKey();
        if (assetID == null || assetID == 0)
            continue; // skip bitcoin

        BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units
        BigInteger sentAmount = sendMap.get(assetID);
        boolean isReceivedAmountMissing = (receivedAmount == null);
        boolean isSentAmountMissing = (sentAmount == null);

        netAmount = BigInteger.ZERO;
        if (!isReceivedAmountMissing)
            netAmount = netAmount.add(receivedAmount);
        if (!isSentAmountMissing)
            netAmount = netAmount.subtract(sentAmount);

        if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) {
            // Catch a case where for a send transaction, the send amount for an asset is 0,
            // but the receive cmount is not 0.  Also the asset was not valid.
            continue;
        }

        CSAsset asset = wallet.CS.getAsset(assetID);
        if (asset == null) {
            // something went wrong, we have asset id but no asset, probably deleted.
            // For now, we carry on, and we display what we know.
        }

        if (netAmount.equals(BigInteger.ZERO) && isSentByMe) {
            // If net asset is 0 and this is our send transaction,
            // we don't need to show anything, as this probably due to implicit transfer.
            // So continue the loop.
            continue;
        }

        if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) {
            // Receiving an asset, where the value is 0 because its not confirmed yet,
            // or not known because asset files not uploaded so we dont know display format.
            // Anyway, we don't do anything here as we do want to display this incoming
            // transaction the best we can.
        }

        //       System.out.println(">>>>     isSentAmountMissing = " + isSentAmountMissing);
        //       System.out.println(">>>>     asset reference = " + asset.getAssetReference());
        //       System.out.println(">>>>     asset name = " + asset.getName());

        String name = null;
        CoinSparkGenesis genesis = null;
        boolean isUnknown = false;
        if (asset != null) {
            genesis = asset.getGenesis();
            name = asset.getNameShort(); // could return null?
        }
        if (name == null) {
            isUnknown = true;
            if (genesis != null) {
                name = "Asset from " + genesis.getDomainName();
            } else {
                // No genesis block found yet
                name = "Other Asset";
            }
        }

        String s1 = null;
        if (asset == null || isUnknown == true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe)) {
            // We don't have formatting details since asset is unknown or deleted
            // If there is a quantity, we don't display it since we don't have display format info
            // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead
            s1 = "...";
        } else {
            BigDecimal displayUnits = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount);
            s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits);
        }

        //
        // Create JSONRPCTransactionAmount and add it to list
        // 
        String fullName = "";
        String assetRef = "";
        if (asset != null) {
            fullName = asset.getName();
            if (fullName == null)
                fullName = name; // use short name
            assetRef = CSMiscUtils.getHumanReadableAssetRef(asset);
        }
        BigDecimal displayQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount);
        JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount();
        amount.setAsset_ref(assetRef);
        amount.setDisplay(s1);
        amount.setName(fullName);
        amount.setName_short(name);
        amount.setQty(displayQty.doubleValue());
        amount.setRaw(netAmount.longValue());
        resultList.add(amount);
    }

    BigInteger satoshiAmount = receiveMap.get(0);
    satoshiAmount = satoshiAmount.subtract(sendMap.get(0));

    // We will show the fee separately so no need to include here.
    if (excludeBTCFee && isSentByMe) {
        BigInteger feeSatoshis = tx.calculateFee(wallet); // returns positive
        if (absoluteBTCFee) {
            satoshiAmount = satoshiAmount.abs().subtract(feeSatoshis);
        } else {
            satoshiAmount = satoshiAmount.add(feeSatoshis);
        }
    }

    String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount) + " BTC";
    BigDecimal satoshiAmountBTC = new BigDecimal(satoshiAmount).divide(new BigDecimal(Utils.COIN));
    JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount();
    amount.setAsset_ref("bitcoin");
    amount.setDisplay(btcAmount);
    amount.setName("Bitcoin");
    amount.setName_short("Bitcoin");
    amount.setQty(satoshiAmountBTC.doubleValue());
    amount.setRaw(satoshiAmount.longValue());
    resultList.add(amount);

    return resultList;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Check the certificate with a list of trusted certificates.
 * The trusted certificates list can either be end entity certificates, in this case, only this certificate by this issuer 
 * is trusted; or it could be CA certificates, in this case, all certificates issued by this CA are trusted.
 * //w  w w.j  a v a  2 s. co  m
 * @param certificate cert to verify
 * @param trustedCertificates collection of trusted X509Certificate
 * @return true if verified OK
 */
public static boolean verifyWithTrustedCertificates(Certificate certificate,
        Collection<Collection<Certificate>> trustedCertificates) {

    if (trustedCertificates == null) {
        if (log.isDebugEnabled()) {
            log.debug("Input of trustedCertificates was null. Trusting nothing.");
        }
        return false;
    }

    if (trustedCertificates.size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("Input of trustedCertificates was empty. Trusting everything.");
        }
        return true;
    }

    BigInteger certSN = getSerialNumber(certificate);
    for (Collection<Certificate> trustedCertChain : trustedCertificates) {
        Certificate trustedCert = trustedCertChain.iterator().next();
        BigInteger trustedCertSN = getSerialNumber(trustedCert);
        if (certSN.equals(trustedCertSN)) {
            // If the serial number of the certificate matches the serial number of a certificate in the list, make sure that it in 
            // fact is the same certificate by verifying that they were issued by the same issuer.
            // Removing this trusted certificate from the trustedCertChain will leave only the CA's certificate chain, which will be 
            // used to verify the issuer.
            if (trustedCertChain.size() > 1) {
                trustedCertChain.remove(trustedCert);
            }
        }
        try {
            verify(certificate, trustedCertChain);
            if (log.isDebugEnabled()) {
                log.debug("Trusting certificate with SubjectDN '" + getSubjectDN(certificate)
                        + "' and issuerDN '" + getIssuerDN(certificate) + "'.");
            }
            return true;
        } catch (Exception e) {
            //Do nothing. Just try the next trusted certificate chain in the list
        }

    }
    return false;
}

From source file:org.opendaylight.vpnservice.elan.internal.ElanInterfaceManager.java

private void removeElanInterface(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {

    BigInteger dpId = interfaceInfo.getDpId();
    String elanName = elanInfo.getElanInstanceName();
    long elanTag = elanInfo.getElanTag();
    String interfaceName = interfaceInfo.getInterfaceName();
    Elan elanState = ElanUtils.getElanByName(elanName);
    logger.debug("Removing the Interface:{} from elan:{}", interfaceName, elanName);
    InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = ElanUtils
            .getElanInterfaceMacEntriesOperationalDataPath(interfaceName);
    Optional<ElanInterfaceMac> existingElanInterface = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL,
            elanInterfaceId);//from   w w w  . j a v  a 2  s . co  m
    if (existingElanInterface.isPresent()) {
        List<PhysAddress> macAddresses = new ArrayList<PhysAddress>();
        List<MacEntry> existingMacEntries = existingElanInterface.get().getMacEntry();
        List<MacEntry> macEntries = new ArrayList<>();
        if (existingMacEntries != null && !existingMacEntries.isEmpty()) {
            macEntries.addAll(existingMacEntries);
        }
        if (!macEntries.isEmpty()) {
            for (MacEntry macEntry : macEntries) {
                logger.debug("removing the  mac-entry:{} present on elanInterface:{}",
                        macEntry.getMacAddress().getValue(), interfaceName);
                elanForwardingEntriesHandler.deleteElanInterfaceForwardingEntries(elanInfo, interfaceInfo,
                        macEntry);
                macAddresses.add(macEntry.getMacAddress());
            }

            // Removing all those MACs from External Devices belonging to this ELAN
            if (elanInfo.getVni() != null && elanInfo.getVni() != 0) {
                ElanL2GatewayUtils.removeMacsFromElanExternalDevices(elanInfo, macAddresses);
            }
        }
    }
    /*
     *This condition check is mainly to get DPN-ID in pre-provision deletion scenario after stopping CSS
     */
    if (dpId.equals(ElanConstants.INVALID_DPN)) {
        ElanDpnInterfacesList elanDpnInterfacesList = ElanUtils.getElanDpnInterfacesList(elanName);
        if (elanDpnInterfacesList != null && !elanDpnInterfacesList.getDpnInterfaces().isEmpty()) {
            List<DpnInterfaces> dpnIfList = elanDpnInterfacesList.getDpnInterfaces();
            for (DpnInterfaces dpnInterface : dpnIfList) {
                DpnInterfaces dpnIfLists = ElanUtils.getElanInterfaceInfoByElanDpn(elanName,
                        dpnInterface.getDpId());
                if (dpnIfLists.getInterfaces().contains(interfaceName)) {
                    logger.debug(
                            "deleting the elanInterface from the ElanDpnInterface cache in pre-provision scenario of elan:{} dpn:{} interfaceName:{}",
                            elanName, dpId, interfaceName);
                    removeElanDpnInterfaceFromOperationalDataStore(elanName, dpId, interfaceName, elanTag);
                    break;
                }
            }
        }
    } else {
        removeElanDpnInterfaceFromOperationalDataStore(elanName, dpId, interfaceName, elanTag);
    }

    removeStaticELanFlows(elanInfo, interfaceInfo);
    ElanUtils.delete(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId);
    List<String> elanInterfaces = elanState.getElanInterfaces();
    elanInterfaces.remove(interfaceName);

    if (elanInterfaces.isEmpty()) {
        ElanUtils.delete(broker, LogicalDatastoreType.OPERATIONAL,
                ElanUtils.getElanInstanceOperationalDataPath(elanName));
        ElanUtils.delete(broker, LogicalDatastoreType.OPERATIONAL,
                ElanUtils.getElanDpnOperationDataPath(elanName));
        ElanUtils.delete(broker, LogicalDatastoreType.OPERATIONAL,
                ElanUtils.getElanMacTableOperationalDataPath(elanName));
        ElanUtils.delete(broker, LogicalDatastoreType.OPERATIONAL,
                ElanUtils.getElanInfoEntriesOperationalDataPath(elanInfo.getElanTag()));
        //ElanUtils.delete(broker, LogicalDatastoreType.CONFIGURATION, ElanUtils.getElanInstanceConfigurationDataPath(elanName));
    } else {
        Elan updateElanState = new ElanBuilder().setElanInterfaces(elanInterfaces).setName(elanName)
                .setKey(new ElanKey(elanName)).build();
        MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL,
                ElanUtils.getElanInstanceOperationalDataPath(elanName), updateElanState);
    }
}

From source file:com.netscape.cms.servlet.cert.DoRevoke.java

/**
 * Process cert status change request//  w  w w  .j  av a 2  s .  c  o  m
 * <P>
 *
 * (Certificate Request - either an "agent" cert status change request, or an "EE" cert status change request)
 * <P>
 *
 * (Certificate Request Processed - either an "agent" cert status change request, or an "EE" cert status change
 * request)
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when a cert status change request (e. g. -
 * "revocation") is made (before approval process)
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a certificate status is
 * changed (revoked, expired, on-hold, off-hold)
 * </ul>
 *
 * @param argSet CMS template parameters
 * @param header argument block
 * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
 *            2 - CA key compromised; should not be used, 3 - Affiliation changed,
 *            4 - Certificate superceded, 5 - Cessation of operation, or
 *            6 - Certificate is on hold)
 * @param invalidityDate certificate validity date
 * @param initiative string containing the audit format
 * @param req HTTP servlet request
 * @param resp HTTP servlet response
 * @param verifiedRecordCount number of verified records
 * @param revokeAll string containing information on all of the
 *            certificates to be revoked
 * @param totalRecordCount total number of records (verified and unverified)
 * @param eeSerialNumber BigInteger containing the end-entity certificate
 *            serial number
 * @param eeSubjectDN string containing the end-entity certificate subject
 *            distinguished name (DN)
 * @param comments string containing certificate comments
 * @param locale the system locale
 * @exception EBaseException an error has occurred
 */
private void process(CMSTemplateParams argSet, IArgBlock header, int reason, Date invalidityDate,
        String initiative, HttpServletRequest req, HttpServletResponse resp, int verifiedRecordCount,
        String revokeAll, int totalRecordCount, BigInteger eeSerialNumber, String eeSubjectDN, String comments,
        Locale locale) throws EBaseException {

    CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber);
    long startTime = CMS.getCurrentDate().getTime();

    RevocationProcessor processor = new RevocationProcessor(servletConfig.getServletName(), getLocale(req));

    processor.setStartTime(startTime);
    processor.setInitiative(initiative);
    processor.setSerialNumber(eeSerialNumber == null ? null : new CertId(eeSerialNumber));

    RevocationReason revReason = RevocationReason.fromInt(reason);
    processor.setRevocationReason(revReason);
    processor.setRequestType(
            processor.getRevocationReason() == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD
                    : RevocationProcessor.REVOKE);

    processor.setInvalidityDate(invalidityDate);
    processor.setComments(comments);

    Hashtable<BigInteger, Long> nonceMap = new Hashtable<BigInteger, Long>();
    X509Certificate clientCert = getSSLClientCertificate(req);

    if (mAuthority instanceof ICertificateAuthority) {
        processor.setAuthority(certAuthority);

        if (certAuthority.noncesEnabled()) {
            String nonces = req.getParameter("nonce");
            if (nonces == null) {
                throw new ForbiddenException("Missing nonce.");
            }

            // parse serial numbers and nonces
            for (String s : nonces.split(",")) {
                String[] elements = s.split(":");
                BigInteger serialNumber = new BigInteger(elements[0].trim());
                Long nonce = new Long(elements[1].trim());
                nonceMap.put(serialNumber, nonce);
            }
        }
    }

    try {
        processor.createCRLExtension();

        if (mAuthority instanceof ICertificateAuthority) {

            Enumeration<ICertRecord> e = mCertDB.searchCertificates(revokeAll, totalRecordCount, mTimeLimits);

            while (e != null && e.hasMoreElements()) {
                ICertRecord targetRecord = e.nextElement();
                X509CertImpl targetCert = targetRecord.getCertificate();

                // Verify end-entity cert is not revoked.
                // TODO: This should be checked during authentication.
                if (eeSerialNumber != null && eeSerialNumber.equals(targetCert.getSerialNumber())
                        && targetRecord.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1",
                            targetRecord.getSerialNumber().toString(16)));

                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

                IArgBlock rarg = CMS.createArgBlock();
                rarg.addStringValue("serialNumber", targetCert.getSerialNumber().toString(16));

                try {
                    if (mAuthority instanceof ICertificateAuthority && certAuthority.noncesEnabled()
                            && !processor.isMemberOfSubsystemGroup(clientCert)) {
                        // validate nonce for each certificate
                        Long nonce = nonceMap.get(targetRecord.getSerialNumber());
                        processor.validateNonce(req, "cert-revoke", targetRecord.getSerialNumber(), nonce);
                    }

                    processor.validateCertificateToRevoke(eeSubjectDN, targetRecord, false);
                    processor.addCertificateToRevoke(targetCert);
                    rarg.addStringValue("error", null);

                } catch (PKIException ex) {
                    rarg.addStringValue("error", ex.getMessage());
                }

                argSet.addRepeatRecord(rarg);
            }

        } else if (mAuthority instanceof IRegistrationAuthority) {
            String reqIdStr = req.getParameter("requestId");
            Collection<CertId> certSerialNumbers = new ArrayList<CertId>();

            if (revokeAll != null && revokeAll.length() > 0) {
                for (int i = revokeAll.indexOf('='); i > -1; i = revokeAll.indexOf('=', i)) {
                    i++;
                    // skip spaces
                    while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
                        i++;
                    }
                    // xxxx decimal serial number?
                    String legalDigits = "0123456789";
                    int j = i;

                    // find legal digits
                    while (j < revokeAll.length() && legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
                        j++;
                    }
                    if (j > i) {
                        certSerialNumbers.add(new CertId(revokeAll.substring(i, j)));
                    }
                }
            }

            if (reqIdStr != null && reqIdStr.length() > 0 && certSerialNumbers.size() > 0) {
                IRequest certReq = mRequestQueue.findRequest(new RequestId(reqIdStr));
                X509CertImpl[] certs = certReq.getExtDataInCertArray(IRequest.OLD_CERTS);
                boolean authorized = false;

                for (int i = 0; i < certs.length; i++) {
                    boolean addToList = false;

                    for (CertId certSerialNumber : certSerialNumbers) {
                        //xxxxx serial number in decimal?
                        if (certs[i].getSerialNumber().equals(certSerialNumber.toBigInteger())
                                && eeSubjectDN != null
                                && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) {
                            addToList = true;
                            break;
                        }
                    }

                    if (eeSerialNumber != null && eeSerialNumber.equals(certs[i].getSerialNumber())) {
                        authorized = true;
                    }

                    if (addToList) {
                        IArgBlock rarg = CMS.createArgBlock();

                        rarg.addStringValue("serialNumber", certs[i].getSerialNumber().toString(16));

                        processor.addCertificateToRevoke(certs[i]);

                        rarg.addStringValue("error", null);
                        argSet.addRepeatRecord(rarg);
                    }
                }

                if (!authorized) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT"));
                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

            } else {
                String b64eCert = req.getParameter("b64eCertificate");

                if (b64eCert != null) {
                    //  BASE64Decoder decoder = new BASE64Decoder();
                    //  byte[] certBytes = decoder.decodeBuffer(b64eCert);
                    byte[] certBytes = Utils.base64decode(b64eCert);
                    X509CertImpl cert = new X509CertImpl(certBytes);
                    IArgBlock rarg = CMS.createArgBlock();

                    rarg.addStringValue("serialNumber", cert.getSerialNumber().toString(16));

                    processor.addCertificateToRevoke(cert);

                    rarg.addStringValue("error", null);
                    argSet.addRepeatRecord(rarg);
                }
            }
        }

        int count = processor.getCertificates().size();
        if (count == 0) {
            processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
            throw new ECMSGWException(CMS.getLogMessage("CMSGW_REVOCATION_ERROR_CERT_NOT_FOUND"));
        }

        header.addIntegerValue("totalRecordCount", count);

        processor.createRevocationRequest();

        processor.auditChangeRequest(ILogger.SUCCESS);

    } catch (ForbiddenException e) {
        throw new EAuthzException(CMS.getUserMessage(locale, "CMS_AUTHORIZATION_ERROR"));

    } catch (CertificateException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        // TODO: throw exception or return?
        // throw new EBaseException(e.getMessage());
        return;

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        throw e;

    } catch (IOException e) {
        processor.log(ILogger.LL_FAILURE,
                CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
        processor.auditChangeRequest(ILogger.FAILURE);

        throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED"));
    }

    // change audit processing from "REQUEST" to "REQUEST_PROCESSED"
    // to distinguish which type of signed audit log message to save
    // as a failure outcome in case an exception occurs

    try {
        processor.processRevocationRequest();
        IRequest revReq = processor.getRequest();

        // retrieve the request status
        RequestStatus status = revReq.getRequestStatus();
        processor.setRequestStatus(status);

        String type = revReq.getRequestType();

        // The SVC_PENDING check has been added for the Cloned CA request
        // that is meant for the Master CA. From Clone's point of view
        // the request is complete

        if (status == RequestStatus.COMPLETE
                || status == RequestStatus.SVC_PENDING && type.equals(IRequest.CLA_CERT4CRL_REQUEST)) {

            header.addStringValue("revoked", "yes");

            Integer updateCRLResult = revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);

            if (updateCRLResult != null) {
                header.addStringValue("updateCRL", "yes");
                if (updateCRLResult.equals(IRequest.RES_SUCCESS)) {
                    header.addStringValue("updateCRLSuccess", "yes");
                } else {
                    header.addStringValue("updateCRLSuccess", "no");
                    String crlError = revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);

                    if (crlError != null)
                        header.addStringValue("updateCRLError", crlError);
                }

                // let known crl publishing status too.
                Integer publishCRLResult = revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);

                if (publishCRLResult != null) {
                    if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
                        header.addStringValue("publishCRLSuccess", "yes");
                    } else {
                        header.addStringValue("publishCRLSuccess", "no");
                        String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                        if (publError != null)
                            header.addStringValue("publishCRLError", publError);
                    }
                }
            }

            if (mAuthority instanceof ICertificateAuthority) {
                // let known update and publish status of all crls.
                Enumeration<ICRLIssuingPoint> otherCRLs = ((ICertificateAuthority) mAuthority)
                        .getCRLIssuingPoints();

                while (otherCRLs.hasMoreElements()) {
                    ICRLIssuingPoint crl = otherCRLs.nextElement();
                    String crlId = crl.getId();

                    if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
                        continue;

                    String updateStatusStr = crl.getCrlUpdateStatusStr();
                    Integer updateResult = revReq.getExtDataInInteger(updateStatusStr);

                    if (updateResult != null) {
                        if (updateResult.equals(IRequest.RES_SUCCESS)) {
                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER", updateStatusStr));
                            header.addStringValue(updateStatusStr, "yes");

                        } else {
                            String updateErrorStr = crl.getCrlUpdateErrorStr();

                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO", updateStatusStr));
                            header.addStringValue(updateStatusStr, "no");
                            String error = revReq.getExtDataInString(updateErrorStr);

                            if (error != null)
                                header.addStringValue(updateErrorStr, error);
                        }

                        String publishStatusStr = crl.getCrlPublishStatusStr();
                        Integer publishResult = revReq.getExtDataInInteger(publishStatusStr);

                        if (publishResult == null)
                            continue;

                        if (publishResult.equals(IRequest.RES_SUCCESS)) {
                            header.addStringValue(publishStatusStr, "yes");

                        } else {
                            String publishErrorStr = crl.getCrlPublishErrorStr();
                            header.addStringValue(publishStatusStr, "no");
                            String error = revReq.getExtDataInString(publishErrorStr);

                            if (error != null)
                                header.addStringValue(publishErrorStr, error);
                        }
                    }
                }
            }

            if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
                header.addStringValue("dirEnabled", "yes");
                Integer[] ldapPublishStatus = revReq.getExtDataInIntegerArray("ldapPublishStatus");
                int certsToUpdate = 0;
                int certsUpdated = 0;

                if (ldapPublishStatus != null) {
                    certsToUpdate = ldapPublishStatus.length;
                    for (int i = 0; i < certsToUpdate; i++) {
                        if (ldapPublishStatus[i] == IRequest.RES_SUCCESS) {
                            certsUpdated++;
                        }
                    }
                }

                header.addIntegerValue("certsUpdated", certsUpdated);
                header.addIntegerValue("certsToUpdate", certsToUpdate);

                // add crl publishing status.
                String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                if (publError != null) {
                    header.addStringValue("crlPublishError", publError);
                }

            } else {
                header.addStringValue("dirEnabled", "no");
            }

            header.addStringValue("error", null);

        } else {
            if (status == RequestStatus.PENDING || status == RequestStatus.REJECTED) {
                header.addStringValue("revoked", status.toString());
            } else {
                header.addStringValue("revoked", "no");
            }

            Vector<String> errors = revReq.getExtDataInStringVector(IRequest.ERRORS);
            if (errors != null) {
                StringBuilder errInfo = new StringBuilder();
                for (int i = 0; i < errors.size(); i++) {
                    errInfo.append(errors.elementAt(i));
                    errInfo.append("\n");
                }
                header.addStringValue("error", errInfo.toString());

            } else if (status == RequestStatus.PENDING) {
                header.addStringValue("error", "Request Pending");

            } else {
                header.addStringValue("error", null);
            }
        }

        processor.auditChangeRequestProcessed(ILogger.SUCCESS);

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequestProcessed(ILogger.FAILURE);

        throw e;
    }
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/**
 * This method takes byte array and translates it onto a OCSPReq class.
 * /*from  w w w.j  av  a 2s  .com*/
 * @param request the byte array in question.
 * @param remoteAddress The remote address of the HttpRequest associated with this array.
 * @param transactionLogger A transaction logger.
 * @return
 * @throws MalformedRequestException
 * @throws SignRequestException thrown if an unsigned request was processed when system configuration requires that all requests be signed.
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws SignRequestSignatureException
 */
private OCSPReq translateRequestFromByteArray(byte[] request, String remoteAddress,
        TransactionLogger transactionLogger) throws MalformedRequestException, SignRequestException,
        SignRequestSignatureException, CertificateException, NoSuchAlgorithmException {
    final OCSPReq ocspRequest;
    try {
        ocspRequest = new OCSPReq(request);
    } catch (IOException e) {
        throw new MalformedRequestException("Could not form OCSP request", e);
    }
    if (ocspRequest.getRequestorName() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is null");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is: " + ocspRequest.getRequestorName().toString());
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.REQ_NAME, ocspRequest.getRequestorName().toString());
        }
    }

    /**
     * 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 (log.isDebugEnabled()) {
        log.debug("Incoming OCSP request is signed : " + ocspRequest.isSigned());
    }
    if (ocspRequest.isSigned()) {
        final X509Certificate signercert = checkRequestSignature(remoteAddress, ocspRequest);
        final String signercertIssuerName = CertTools.getIssuerDN(signercert);
        final BigInteger signercertSerNo = CertTools.getSerialNumber(signercert);
        final String signercertSubjectName = CertTools.getSubjectDN(signercert);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName);
            transactionLogger.paramPut(TransactionLogger.SIGN_SERIAL_NO,
                    signercert.getSerialNumber().toByteArray());
            transactionLogger.paramPut(TransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName);
            transactionLogger.paramPut(PatternLogger.REPLY_TIME, TransactionLogger.REPLY_TIME);
        }
        // Check if we have configured request verification using the old property file way..
        boolean enforceRequestSigning = OcspConfiguration.getEnforceRequestSigning();
        // Next, check if there is an OcspKeyBinding where signing is required and configured for this request
        // In the case where multiple requests are bundled together they all must be trusting the signer
        for (final Req req : ocspRequest.getRequestList()) {
            OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID());
            if (ocspSigningCacheEntry == null) {
                if (log.isTraceEnabled()) {
                    log.trace("Using default responder to check signature.");
                }
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
            }
            if (ocspSigningCacheEntry != null
                    && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                if (log.isTraceEnabled()) {
                    log.trace("ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate: "
                            + ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate());
                }
                final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding();
                if (log.isTraceEnabled()) {
                    log.trace("OcspKeyBinding " + ocspKeyBinding.getId() + ", RequireTrustedSignature: "
                            + ocspKeyBinding.getRequireTrustedSignature());
                }
                if (ocspKeyBinding.getRequireTrustedSignature()) {
                    enforceRequestSigning = true;
                    boolean isTrusted = false;
                    final List<InternalKeyBindingTrustEntry> trustedCertificateReferences = ocspKeyBinding
                            .getTrustedCertificateReferences();
                    if (trustedCertificateReferences.isEmpty()) {
                        // We trust ANY cert from a known CA
                        isTrusted = true;
                    } else {
                        for (final InternalKeyBindingTrustEntry trustEntry : trustedCertificateReferences) {
                            final int trustedCaId = trustEntry.getCaId();
                            final BigInteger trustedSerialNumber = trustEntry.fetchCertificateSerialNumber();
                            if (log.isTraceEnabled()) {
                                log.trace("Processing trustedCaId=" + trustedCaId + " trustedSerialNumber="
                                        + trustedSerialNumber + " signercertIssuerName.hashCode()="
                                        + signercertIssuerName.hashCode() + " signercertSerNo="
                                        + signercertSerNo);
                            }
                            if (trustedCaId == signercertIssuerName.hashCode()) {
                                if (trustedSerialNumber == null) {
                                    // We trust any certificate from this CA
                                    isTrusted = true;
                                    if (log.isTraceEnabled()) {
                                        log.trace(
                                                "Trusting request signature since ANY certificate from issuer "
                                                        + trustedCaId + " is trusted.");
                                    }
                                    break;
                                } else if (signercertSerNo.equals(trustedSerialNumber)) {
                                    // We trust this particular certificate from this CA
                                    isTrusted = true;
                                    if (log.isTraceEnabled()) {
                                        log.trace(
                                                "Trusting request signature since certificate with serialnumber "
                                                        + trustedSerialNumber + " from issuer " + trustedCaId
                                                        + " is trusted.");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    if (!isTrusted) {
                        final String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed",
                                signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16));
                        log.info(infoMsg);
                        throw new SignRequestSignatureException(infoMsg);
                    }
                }
            }
        }
        if (enforceRequestSigning) {
            // If it verifies OK, check if it is revoked
            final CertificateStatus status = certificateStoreSession.getStatus(signercertIssuerName,
                    signercertSerNo);
            /*
             * 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);
                log.info(infoMsg);
                throw new SignRequestSignatureException(infoMsg);
            }
        }
    } else {
        if (OcspConfiguration.getEnforceRequestSigning()) {
            // Signature required
            throw new SignRequestException("Signature required");
        }
        // Next, check if there is an OcspKeyBinding where signing is required and configured for this request
        // In the case where multiple requests are bundled together they all must be trusting the signer
        for (final Req req : ocspRequest.getRequestList()) {
            OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID());
            if (ocspSigningCacheEntry == null) {
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
            }
            if (ocspSigningCacheEntry != null
                    && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding();
                if (ocspKeyBinding.getRequireTrustedSignature()) {
                    throw new SignRequestException("Signature required");
                }
            }
        }
    }
    return ocspRequest;
}

From source file:com.peterbochs.PeterBochsDebugger.java

public void updateBreakpointTableColor() {
    for (int x = 0; x < breakpointTable.getRowCount(); x++) {
        String value = breakpointTable.getValueAt(x, 0).toString();
        InstructionTableModel model = (InstructionTableModel) instructionTable.getModel();
        BigInteger currentIP = CommonLib.string2BigInteger(registerPanel.eipTextField.getText());
        if (currentIP.equals(CommonLib.string2BigInteger(breakpointTable.getValueAt(x, 2).toString()))) {
            int hit = Integer.parseInt(breakpointTable.getValueAt(x, 3).toString());
            breakpointTable.setValueAt("-" + value, x, 0);
            breakpointTable.setValueAt(hit + 1, x, 3);
        } else {//  ww w.  j  a  v a2 s  .co  m
            if (value.startsWith("-")) {
                breakpointTable.setValueAt(value.substring(1), x, 0);
            }
        }
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

private String getASMCode(BigInteger pc) {
    for (int x = 0; x < instructionTable.getRowCount(); x++) {
        String col1 = instructionTable.getValueAt(x, 1).toString();
        if (col1.startsWith("cCode")) {
            continue;
        }/*from www .ja va2 s  .c  om*/
        BigInteger address = CommonLib.string2BigInteger(col1.toString());
        if (pc.equals(address)) {
            return instructionTable.getValueAt(x, 2).toString();
        }
    }
    return null;
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void nexti(BigInteger addr, String command) {
    //      System.out.println("going to " + addr.toString(16));
    BigInteger currentEIP = getRealEIP();
    for (int x = 0; x < Global.MAX_NEXTI_INSTRUCTION_COUNT; x++) {
        String asmCode = getASMCode(currentEIP);
        sendCommand(command);/*from  w  w  w  . ja  v a2  s. c o  m*/
        updateRegister(true);
        waitUpdateFinish();
        currentEIP = getRealEIP();
        if (currentEIP.equals(addr)) {
            break;
        }

        if (asmCode != null && asmCode.contains("call")) {
            System.out.println("bingo la " + asmCode);
            break;
        }
    }

    //      updateBochsStatus(true);

    updateRegister(true);
    updateEFlags();
    updateMemory(true);
    updateInstruction(null);
    updateBreakpoint();
    updateBreakpointTableColor();
    updateHistoryTable();
    waitUpdateFinish();
    jumpToRowInstructionTable(getRealEIP());
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void nextButtonActionPerformed(ActionEvent evt) {
    BigInteger currentIP = CommonLib.string2BigInteger(registerPanel.eipTextField.getText());
    String nextCCode = null;//from   w ww.j  ava 2s .c  om
    boolean bingo = false;
    BigInteger addr = null;
    for (int x = 0; x < instructionTable.getRowCount() - 1; x++) {
        String addressColumn = (String) instructionTable.getValueAt(x, 1);
        if (addressColumn.startsWith("cCode")) {
            addr = CommonLib.string2BigInteger(addressColumn.split(":")[1]);
        } else {
            addr = CommonLib.string2BigInteger(addressColumn);
        }
        if (bingo && addressColumn.startsWith("cCode") && !addr.equals(currentIP)) {
            nextCCode = addressColumn;
            break;
        }
        if (addr != null && addr.equals(currentIP)) {
            bingo = true;
        }
    }

    if (addr != null) {
        nexti(addr, "s");
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void nextOverButtonActionPerformed(ActionEvent evt) {
    BigInteger currentIP = CommonLib.string2BigInteger(registerPanel.eipTextField.getText());
    String nextCCode = null;//w  w  w . j  a  v a2s .c om
    boolean bingo = false;
    BigInteger addr = null;
    for (int x = 0; x < instructionTable.getRowCount() - 1; x++) {
        String addressColumn = (String) instructionTable.getValueAt(x, 1);
        if (addressColumn.startsWith("cCode")) {
            addr = CommonLib.string2BigInteger(addressColumn.split(":")[1]);
        } else {
            addr = CommonLib.string2BigInteger(addressColumn);
        }
        if (bingo && addressColumn.startsWith("cCode") && !addr.equals(currentIP)) {
            nextCCode = addressColumn;
            break;
        }
        if (addr != null && addr.equals(currentIP)) {
            bingo = true;
        }
    }

    if (addr != null) {
        nexti(addr, "next");
    }
}