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:info.savestate.saveybot.JSONFileManipulator.java

private String getSlot(BigInteger slot) {
    JSONArray json = getJSON();/*from  www. java  2s .c  om*/
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        if (o == null)
            continue;
        BigInteger current = new BigInteger(o.getString("slot"));
        if (current.equals(slot))
            return o.getString("message");
    }
    return "that savestate doesnt exist !!! (u should make it)";
}

From source file:org.eclipse.om2m.binding.coap.CoapClient.java

/**
 * Converts a protocol-independent {@link RequestIndication} object into a
 * standard CoAP request and sends a standard CoAP request. Converts the
 * received standard CoAP response into {@link ResponseConfirm} object and
 * returns it back./*from   www  .j a va  2 s  .  co  m*/
 * 
 * @param requestIndication
 *            - protocol independent request.
 * @return protocol independent response.
 */
public ResponsePrimitive sendRequest(RequestPrimitive requestPrimitive) {
    LOGGER.debug("Sending request with CoAP binding: " + requestPrimitive);

    // Retrieve the url
    String url = requestPrimitive.getTo();
    if (!url.startsWith(protocol + "://")) {
        if (url.startsWith("://")) {
            url = protocol + url;
        } else if (url.startsWith("//")) {
            url = protocol + ":" + url;
        } else {
            url = protocol + "://" + url;
        }
    }

    // create the standard final response
    ResponsePrimitive responsePrimitive = new ResponsePrimitive();

    // get the Payload from requestIndication
    String representation = requestPrimitive.getContent() != null ? requestPrimitive.getContent().toString()
            : null;

    // create the code in order to create a coap request
    CoAP.Code code = null;

    // get the method from requestIndication
    BigInteger operation = requestPrimitive.getOperation();
    if (operation != null) {
        if (operation.equals(Operation.CREATE)) {
            code = CoAP.Code.POST;
        } else if (operation.equals(Operation.RETRIEVE) || operation.equals(Operation.DISCOVERY)) {
            code = CoAP.Code.GET;
        } else if (operation.equals(Operation.UPDATE)) {
            code = CoAP.Code.PUT;
        } else if (operation.equals(Operation.DELETE)) {
            code = CoAP.Code.DELETE;
        } else if (operation.equals(Operation.NOTIFY)) {
            code = CoAP.Code.POST;
        }
    } else {
        return responsePrimitive;
    }

    // create a coap request
    Request request = new Request(code);

    // get the options of the CoAP request (which is still empty)
    OptionSet options = new OptionSet();
    request.setOptions(options);
    // set the CoAP message Id
    int MId = (int) (1000 + Math.random() * (9001));
    request.setMID(MId);
    // request.setToken(token);
    CoAP.Type coapType = CoAP.Type.CON;
    request.setType(coapType);

    // set the request URI
    request.setURI(url);

    // set the payload
    if (representation != null) {
        request.setPayload(representation);
    }

    // set the content format of the request
    if (requestPrimitive.getRequestContentType() != null) {
        switch (requestPrimitive.getRequestContentType()) {
        case MimeMediaType.XML:
            request.getOptions().setContentFormat(CoapContentType.APP_XML);
            break;
        case MimeMediaType.XML_RESOURCE:
            request.getOptions().setContentFormat(CoapContentType.RES_XML);
            break;
        case MimeMediaType.JSON:
            request.getOptions().setContentFormat(CoapContentType.APP_JSON);
            break;
        case MimeMediaType.JSON_RESOURCE:
            request.getOptions().setContentFormat(CoapContentType.RES_JSON);
        default:
            break;
        }
    }

    // set the accept of the request
    if (requestPrimitive.getReturnContentType() != null) {
        switch (requestPrimitive.getReturnContentType()) {
        case MimeMediaType.XML:
            request.getOptions().setAccept(CoapContentType.APP_XML);
            break;
        case MimeMediaType.XML_RESOURCE:
            request.getOptions().setAccept(CoapContentType.RES_XML);
            break;
        case MimeMediaType.JSON:
            request.getOptions().setAccept(CoapContentType.APP_JSON);
            break;
        case MimeMediaType.JSON_RESOURCE:
            request.getOptions().setAccept(CoapContentType.RES_JSON);
        default:
            break;
        }
    }

    // Set multiple parameters from the request primitive
    if (requestPrimitive.getFrom() != null) {
        options.addOption(new Option(CoapOptions.ONEM2M_FR, requestPrimitive.getFrom()));
    }
    if (requestPrimitive.getRequestIdentifier() != null) {
        options.addOption(new Option(CoapOptions.ONEM2M_RQI, requestPrimitive.getRequestIdentifier()));
    }
    if (requestPrimitive.getResourceType() != null) {
        options.addOption(new Option(CoapOptions.ONEM2M_TY, requestPrimitive.getResourceType().intValue()));
    }
    if (requestPrimitive.getEventCategory() != null) {
        options.addOption(new Option(CoapOptions.ONEM2M_EC, requestPrimitive.getEventCategory()));
    }
    if (!requestPrimitive.getQueryStrings().isEmpty()) {
        for (String queryStringKey : requestPrimitive.getQueryStrings().keySet()) {
            for (String value : requestPrimitive.getQueryStrings().get(queryStringKey)) {
                options.addURIQuery(queryStringKey + "=" + value);
            }
        }
    }
    if (requestPrimitive.getResponseTypeInfo() != null) {
        if (!requestPrimitive.getResponseTypeInfo().getNotificationURI().isEmpty()) {
            String notifUris = "";
            for (String nu : requestPrimitive.getResponseTypeInfo().getNotificationURI()) {
                notifUris += nu + "&";
            }
            if (notifUris.endsWith("&")) {
                notifUris = notifUris.substring(0, notifUris.length() - 1);
            }
            options.addOption(new Option(CoapOptions.ONEM2M_RTURI, notifUris));
        }
        if (requestPrimitive.getResponseTypeInfo().getResponseType() != null) {
            options.addURIQuery(CoapParameters.RESPONSE_TYPE + "="
                    + requestPrimitive.getResponseTypeInfo().getResponseType());
        }
    }

    if (requestPrimitive.getResultPersistence() != null) {
        options.addURIQuery(CoapParameters.RESULT_PERSISTENCE + "=" + requestPrimitive.getResultPersistence());
    }

    if (requestPrimitive.getResultContent() != null) {
        options.addURIQuery(CoapParameters.RESULT_CONTENT + "=" + requestPrimitive.getResultContent());
    }

    if (requestPrimitive.getDiscoveryResultType() != null) {
        options.addURIQuery(
                CoapParameters.DISCOVERY_RESULT_TYPE + "=" + requestPrimitive.getDiscoveryResultType());
    }

    // Set the filter criteria parameters
    if (requestPrimitive.getFilterCriteria() != null) {
        FilterCriteria filter = requestPrimitive.getFilterCriteria();
        if (!filter.getAttribute().isEmpty()) {
            for (Attribute att : filter.getAttribute()) {
                options.addURIQuery(att.getName() + "=" + att.getValue());
            }
        }
        if (filter.getFilterUsage() != null) {
            options.addURIQuery(CoapParameters.FILTER_USAGE + "=" + filter.getFilterUsage());
        }
        if (!filter.getLabels().isEmpty()) {
            for (String label : filter.getLabels()) {
                options.addURIQuery(CoapParameters.LABELS + "=" + label);
            }
        }
        if (filter.getLimit() != null) {
            options.addURIQuery(CoapParameters.LIMIT + "=" + filter.getLimit());
        }
        if (filter.getResourceType() != null) {
            options.addURIQuery(CoapParameters.RESOURCE_TYPE + "=" + filter.getResourceType());
        }
    }

    if (requestPrimitive.getGroupRequestIdentifier() != null) {
        options.addOption(new Option(CoapOptions.ONEM2M_GID, requestPrimitive.getGroupRequestIdentifier()));
    }

    // send the request
    request.setScheme(url);
    request.send();

    // get the response
    Response response = null;
    try {
        response = request.waitForResponse();
    } catch (InterruptedException e) {
        LOGGER.error("CoAP Client > Failed to receive response: " + e.getMessage(), e);
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
        responsePrimitive.setContent("Target is not reachable");
        responsePrimitive.setContentType(MimeMediaType.TEXT_PLAIN);
        return responsePrimitive;
    }
    if (response != null) {
        if (response.getOptions().hasContentFormat(MediaTypeRegistry.APPLICATION_LINK_FORMAT)) {

            String linkFormat = response.getPayloadString();
            // fill in the representation of the responsePrimitive
            responsePrimitive.setContent(linkFormat);
        } else {
            responsePrimitive.setContent(response.getPayloadString());
        }
    }

    // Parse response options
    List<Option> optionsList = response.getOptions().asSortedList();
    for (Option o : optionsList) {
        switch (o.getNumber()) {
        case CoapOptions.ONEM2M_FR:
            responsePrimitive.setFrom(o.getStringValue());
            break;
        case CoapOptions.ONEM2M_RQI:
            responsePrimitive.setRequestIdentifier(o.getStringValue());
            break;
        case CoapOptions.ONEM2M_RSC:
            responsePrimitive.setResponseStatusCode(BigInteger.valueOf(o.getIntegerValue()));
            break;
        case CoapOptions.LOCATION:
            responsePrimitive.setLocation(o.getStringValue());
            break;
        default:
            LOGGER.trace("Option not handled: " + o.getNumber());
        }
    }

    if (responsePrimitive.getResponseStatusCode() == null) {
        responsePrimitive.setResponseStatusCode(getResponseStatusCode(response.getCode().value));
    }
    switch (response.getOptions().getContentFormat()) {
    case CoapContentType.APP_XML:
        responsePrimitive.setContentType(MimeMediaType.XML);
        break;
    case CoapContentType.RES_XML:
        responsePrimitive.setContentType(MimeMediaType.XML_RESOURCE);
        break;
    case CoapContentType.APP_JSON:
        responsePrimitive.setContentType(MimeMediaType.JSON);
        break;
    case CoapContentType.RES_JSON:
        responsePrimitive.setContentType(MimeMediaType.JSON_RESOURCE);
    }
    LOGGER.debug("CoAP Client > " + responsePrimitive);
    return responsePrimitive;
}

From source file:org.cesecore.mock.authentication.tokens.TestX509CertificateAuthenticationToken.java

@Override
public boolean matches(AccessUserAspect accessUser) {
    boolean returnvalue = false;

    int parameter;
    int size = 0;
    String[] clientstrings = null;
    if (StringUtils.equals(TOKEN_TYPE, accessUser.getTokenType())) {
        // First check that issuers match.
        if (accessUser.getCaId() == adminCaId) {
            // Determine part of certificate to match with.
            DNFieldExtractor usedExtractor = dnExtractor;
            X500PrincipalAccessMatchValue matchValue = (X500PrincipalAccessMatchValue) getMatchValueFromDatabaseValue(
                    accessUser.getMatchWith());
            if (matchValue == X500PrincipalAccessMatchValue.WITH_SERIALNUMBER) {
                try {
                    BigInteger matchValueAsBigInteger = new BigInteger(accessUser.getMatchValue(), 16);
                    switch (accessUser.getMatchTypeAsType()) {
                    case TYPE_EQUALCASE:
                    case TYPE_EQUALCASEINS:
                        returnvalue = matchValueAsBigInteger.equals(certificate.getSerialNumber());
                        break;
                    case TYPE_NOT_EQUALCASE:
                    case TYPE_NOT_EQUALCASEINS:
                        returnvalue = !matchValueAsBigInteger.equals(certificate.getSerialNumber());
                        break;
                    default:
                    }/* w  w  w  .  ja v a  2s  . c  o m*/
                } catch (NumberFormatException nfe) {
                    log.info("Invalid matchValue for accessUser when expecting a hex serialNumber: "
                            + accessUser.getMatchValue());
                }
            } else if (matchValue == X500PrincipalAccessMatchValue.WITH_FULLDN) {
                String value = accessUser.getMatchValue();
                switch (accessUser.getMatchTypeAsType()) {
                case TYPE_EQUALCASE:
                    returnvalue = value.equals(CertTools.getSubjectDN(certificate));
                case TYPE_EQUALCASEINS:
                    returnvalue = value.equalsIgnoreCase(CertTools.getSubjectDN(certificate));
                    break;
                case TYPE_NOT_EQUALCASE:
                    returnvalue = !value.equals(CertTools.getSubjectDN(certificate));
                case TYPE_NOT_EQUALCASEINS:
                    returnvalue = !value.equalsIgnoreCase(CertTools.getSubjectDN(certificate));
                    break;
                default:
                }
            } else {
                parameter = DNFieldExtractor.CN;
                switch (matchValue) {
                case WITH_COUNTRY:
                    parameter = DNFieldExtractor.C;
                    break;
                case WITH_DOMAINCOMPONENT:
                    parameter = DNFieldExtractor.DC;
                    break;
                case WITH_STATEORPROVINCE:
                    parameter = DNFieldExtractor.ST;
                    break;
                case WITH_LOCALITY:
                    parameter = DNFieldExtractor.L;
                    break;
                case WITH_ORGANIZATION:
                    parameter = DNFieldExtractor.O;
                    break;
                case WITH_ORGANIZATIONALUNIT:
                    parameter = DNFieldExtractor.OU;
                    break;
                case WITH_TITLE:
                    parameter = DNFieldExtractor.T;
                    break;
                case WITH_DNSERIALNUMBER:
                    parameter = DNFieldExtractor.SN;
                    break;
                case WITH_COMMONNAME:
                    parameter = DNFieldExtractor.CN;
                    break;
                case WITH_UID:
                    parameter = DNFieldExtractor.UID;
                    break;
                case WITH_DNEMAILADDRESS:
                    parameter = DNFieldExtractor.E;
                    break;
                case WITH_RFC822NAME:
                    parameter = DNFieldExtractor.RFC822NAME;
                    usedExtractor = anExtractor;
                    break;
                case WITH_UPN:
                    parameter = DNFieldExtractor.UPN;
                    usedExtractor = anExtractor;
                    break;
                default:
                }
                size = usedExtractor.getNumberOfFields(parameter);
                clientstrings = new String[size];
                for (int i = 0; i < size; i++) {
                    clientstrings[i] = usedExtractor.getField(parameter, i);
                }

                // Determine how to match.
                if (clientstrings != null) {
                    switch (accessUser.getMatchTypeAsType()) {
                    case TYPE_EQUALCASE:
                        for (int i = 0; i < size; i++) {
                            returnvalue = clientstrings[i].equals(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_EQUALCASEINS:
                        for (int i = 0; i < size; i++) {
                            returnvalue = clientstrings[i].equalsIgnoreCase(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_NOT_EQUALCASE:
                        for (int i = 0; i < size; i++) {
                            returnvalue = !clientstrings[i].equals(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_NOT_EQUALCASEINS:
                        for (int i = 0; i < size; i++) {
                            returnvalue = !clientstrings[i].equalsIgnoreCase(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    default:
                    }
                }
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace(
                        "Caid does not match. Required=" + adminCaId + ", actual was " + accessUser.getCaId());
            }
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Token type does not match. Required=" + TOKEN_TYPE + ", actual was "
                    + accessUser.getTokenType());
        }
    }

    return returnvalue;
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key//from  w w w . j  a v a  2s.  co  m
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();

    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);

    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(
                calculatorProviderBuilder.get(CertificateID.HASH_SHA1),
                new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);

        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);

        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
                new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));

        final OCSPReq ocspRequest = requestGenerator.build();

        // perform the request
        final ClientResponse response = getClientResponse(ocspRequest);

        // ensure the request was completed successfully
        if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }

        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.getEntityInputStream());

        // verify the response status
        switch (ocspResponse.getStatus()) {
        case OCSPRespBuilder.SUCCESSFUL:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
            break;
        case OCSPRespBuilder.INTERNAL_ERROR:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
            break;
        case OCSPRespBuilder.MALFORMED_REQUEST:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
            break;
        case OCSPRespBuilder.SIG_REQUIRED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
            break;
        case OCSPRespBuilder.TRY_LATER:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
            break;
        case OCSPRespBuilder.UNAUTHORIZED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
            break;
        default:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
            break;
        }

        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).",
                    ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }

        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }

        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s",
                    responderCertificates.length));
            return ocspStatus;
        }

        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(
                responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC")
                    .build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }

        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();

            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();

                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | UniformInterfaceException | ClientHandlerException
            | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }

    return ocspStatus;
}

From source file:info.savestate.saveybot.JSONFileManipulator.java

public String saveSlot(String slotString, String username, String message) {
    BigInteger slot;//from   ww w  .  ja v  a2  s .  com
    try {
        slot = new BigInteger(slotString);
    } catch (Exception e) {
        return "lmao bye af thats not a real number";
    }
    JSONArray json = getJSON();
    int replaceIndex = -1;
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        if (o == null)
            continue;
        BigInteger current = new BigInteger(o.getString("slot"));
        if (current.equals(slot)) {
            if (!o.getString("name").equals(username)) {
                return "waohwo!!! " + o.getString("name") + " owns this savestate you dong !!";
            } else {
                replaceIndex = i;
                break;
            }
        }
    }
    JSONObject o = new JSONObject();
    o.put("name", username);
    o.put("slot", slot.toString());
    o.put("message", message);
    if (replaceIndex != -1) {
        json.remove(replaceIndex);
        json.put(replaceIndex, o);
    } else
        json.put(o);
    writeJSON(json);
    return "ur savestate was sav'd to slot " + slot.toString() + "! ^O^";
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

public static List<TzMembership> getOriginalTzMembership(TunnelEndPoints srcTep, BigInteger dpnId,
        List<DPNTEPsInfo> meshedDpnList) {
    LOG.trace("Original Membership for source DPN {}, source TEP {}", dpnId, srcTep);
    for (DPNTEPsInfo dstDpn : meshedDpnList) {
        if (dpnId.equals(dstDpn.getDPNID())) {
            List<TunnelEndPoints> endPts = dstDpn.getTunnelEndPoints();
            for (TunnelEndPoints tep : endPts) {
                if (tep.getIpAddress().equals(srcTep.getIpAddress())) {
                    LOG.debug("Original Membership size " + tep.getTzMembership().size());
                    return tep.getTzMembership();
                }//  ww w.ja  v a  2s .  co  m
            }
        }
    }
    return null;
}

From source file:org.opendaylight.vpnservice.elan.utils.ElanUtils.java

public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
        boolean deleteSmac) {
    String elanInstanceName = elanInfo.getElanInstanceName();
    long ifTag = interfaceInfo.getInterfaceTag();
    List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
    BigInteger srcdpId = interfaceInfo.getDpId();
    for (DpnInterfaces dpnInterface : remoteFEs) {
        Long elanTag = elanInfo.getElanTag();
        BigInteger dstDpId = dpnInterface.getDpId();
        if (dstDpId.equals(srcdpId)) {
            if (deleteSmac) {
                mdsalMgr.removeFlow(srcdpId,
                        MDSALUtil.buildFlow(ElanConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
                                ElanConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
            }//from   ww  w. j  a v  a  2  s.c  om
            mdsalMgr.removeFlow(srcdpId,
                    MDSALUtil.buildFlow(ElanConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
                            ElanConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "All the required flows deleted for elan:{}, logical Interface port:{} and mac address:{} on dpn:{}",
                        elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
            }
        } else if (isDpnPresent(dstDpId)) {
            mdsalMgr.removeFlow(dstDpId,
                    MDSALUtil.buildFlow(ElanConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
                            ElanConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
                        elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
            }
        }
    }
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBTest.java

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {// ww  w . j a v  a 2s. c  o m

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            X509Certificate certificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);

            certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = StringUtils.EMPTY;
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Base64.encode(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        IOUtils.closeQuietly(asn1sInput);
        IOUtils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRARequestCustomSerialNoTest.java

@Test
public void test01CustomCertificateSerialNumber() throws Exception {
    final KeyPair key1 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final String userName1 = "cmptest1";
    final X500Name userDN1 = new X500Name("C=SE,O=PrimeKey,CN=" + userName1);
    try {/*from w  w w  .j  a  v  a2 s  .c  om*/
        // check that several certificates could be created for one user and one key.
        long serno = RandomUtils.nextLong();
        BigInteger bint = BigInteger.valueOf(serno);
        // First it should fail because the CMP RA does not even look for, or parse, requested custom certificate serial numbers
        // Actually it does not fail here, but returns good answer
        X509Certificate cert = crmfHttpUserTest(userDN1, key1, null, null);
        assertFalse("SerialNumbers should not be equal when custom serialnumbers are not allowed.",
                bint.equals(cert.getSerialNumber()));

        // Second it should fail when the certificate profile does not allow serial number override
        // crmfHttpUserTest checks the returned serno if bint parameter is not null
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        crmfHttpUserTest(userDN1, key1, "Used certificate profile ('" + this.cpDnOverrideId
                + "') is not allowing certificate serial number override.", bint);

        // Third it should succeed and we should get our custom requested serialnumber
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        CertificateProfile cp = this.certProfileSession.getCertificateProfile(this.cpDnOverrideId);
        cp.setAllowCertSerialNumberOverride(true);
        // Now when the profile allows serial number override it should work
        this.certProfileSession.changeCertificateProfile(ADMIN, CP_DN_OVERRIDE_NAME, cp);
        crmfHttpUserTest(userDN1, key1, null, bint);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, userName1);
        } catch (NotFoundException e) {
            /* do nothing */}
    }
}

From source file:org.cesecore.authentication.tokens.X509CertificateAuthenticationToken.java

/**
 * This implementation presumes that a lone {@link X509Certificate} has been submitted as a credential (which should have been verified by the
 * constructor), and will use that value to match this authentication token to the AccessUserData entity submitted.
 * //from  ww w.j a  v  a 2s. c o m
 * FIXME: This class is a candidate for optimization. 
 * FIXME: Attempt to remove as many static calls as possible.
 * 
 */
@Override
public boolean matches(AccessUserAspect accessUser) {
    // Protect against spoofing by checking if this token was created locally
    if (!super.isCreatedInThisJvm()) {
        return false;
    }
    boolean returnvalue = false;

    int parameter;
    int size = 0;
    String[] clientstrings = null;
    if (StringUtils.equals(TOKEN_TYPE, accessUser.getTokenType())) {
        // First check that issuers match.
        if (accessUser.getCaId() == adminCaId) {
            // Determine part of certificate to match with.
            DNFieldExtractor usedExtractor = dnExtractor;
            X500PrincipalAccessMatchValue matchValue = (X500PrincipalAccessMatchValue) getMatchValueFromDatabaseValue(
                    accessUser.getMatchWith());
            if (matchValue == X500PrincipalAccessMatchValue.WITH_SERIALNUMBER) {
                try {
                    BigInteger matchValueAsBigInteger = new BigInteger(accessUser.getMatchValue(), 16);
                    switch (accessUser.getMatchTypeAsType()) {
                    case TYPE_EQUALCASE:
                    case TYPE_EQUALCASEINS:
                        returnvalue = matchValueAsBigInteger.equals(certificate.getSerialNumber());
                        break;
                    case TYPE_NOT_EQUALCASE:
                    case TYPE_NOT_EQUALCASEINS:
                        returnvalue = !matchValueAsBigInteger.equals(certificate.getSerialNumber());
                        break;
                    default:
                    }
                } catch (NumberFormatException nfe) {
                    log.info("Invalid matchValue for accessUser when expecting a hex serialNumber: "
                            + accessUser.getMatchValue());
                }
            } else if (matchValue == X500PrincipalAccessMatchValue.WITH_FULLDN) {
                String value = accessUser.getMatchValue();
                switch (accessUser.getMatchTypeAsType()) {
                case TYPE_EQUALCASE:
                    returnvalue = value.equals(CertTools.getSubjectDN(certificate));
                case TYPE_EQUALCASEINS:
                    returnvalue = value.equalsIgnoreCase(CertTools.getSubjectDN(certificate));
                    break;
                case TYPE_NOT_EQUALCASE:
                    returnvalue = !value.equals(CertTools.getSubjectDN(certificate));
                case TYPE_NOT_EQUALCASEINS:
                    returnvalue = !value.equalsIgnoreCase(CertTools.getSubjectDN(certificate));
                    break;
                default:
                }
            } else {
                parameter = DNFieldExtractor.CN;
                switch (matchValue) {
                case WITH_COUNTRY:
                    parameter = DNFieldExtractor.C;
                    break;
                case WITH_DOMAINCOMPONENT:
                    parameter = DNFieldExtractor.DC;
                    break;
                case WITH_STATEORPROVINCE:
                    parameter = DNFieldExtractor.ST;
                    break;
                case WITH_LOCALITY:
                    parameter = DNFieldExtractor.L;
                    break;
                case WITH_ORGANIZATION:
                    parameter = DNFieldExtractor.O;
                    break;
                case WITH_ORGANIZATIONALUNIT:
                    parameter = DNFieldExtractor.OU;
                    break;
                case WITH_TITLE:
                    parameter = DNFieldExtractor.T;
                    break;
                case WITH_DNSERIALNUMBER:
                    parameter = DNFieldExtractor.SN;
                    break;
                case WITH_COMMONNAME:
                    parameter = DNFieldExtractor.CN;
                    break;
                case WITH_UID:
                    parameter = DNFieldExtractor.UID;
                    break;
                case WITH_DNEMAILADDRESS:
                    parameter = DNFieldExtractor.E;
                    break;
                case WITH_RFC822NAME:
                    parameter = DNFieldExtractor.RFC822NAME;
                    usedExtractor = anExtractor;
                    break;
                case WITH_UPN:
                    parameter = DNFieldExtractor.UPN;
                    usedExtractor = anExtractor;
                    break;
                default:
                }
                size = usedExtractor.getNumberOfFields(parameter);
                clientstrings = new String[size];
                for (int i = 0; i < size; i++) {
                    clientstrings[i] = usedExtractor.getField(parameter, i);
                }

                // Determine how to match.
                if (clientstrings != null) {
                    switch (accessUser.getMatchTypeAsType()) {
                    case TYPE_EQUALCASE:
                        for (int i = 0; i < size; i++) {
                            returnvalue = clientstrings[i].equals(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_EQUALCASEINS:
                        for (int i = 0; i < size; i++) {
                            returnvalue = clientstrings[i].equalsIgnoreCase(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_NOT_EQUALCASE:
                        for (int i = 0; i < size; i++) {
                            returnvalue = !clientstrings[i].equals(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    case TYPE_NOT_EQUALCASEINS:
                        for (int i = 0; i < size; i++) {
                            returnvalue = !clientstrings[i].equalsIgnoreCase(accessUser.getMatchValue());
                            if (returnvalue) {
                                break;
                            }
                        }
                        break;
                    default:
                    }
                }
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace(
                        "Caid does not match. Required=" + adminCaId + ", actual was " + accessUser.getCaId());
            }
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Token type does not match. Required=" + TOKEN_TYPE + ", actual was "
                    + accessUser.getTokenType());
        }
    }

    return returnvalue;
}