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:de.schildbach.litecoinwallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*www .j  av  a 2 s  .c o  m*/
    updateView();

    // create spend
    final BigInteger amount = amountCalculatorLink.getAmount();
    final SendRequest sendRequest = SendRequest.to(validatedAddress.address, amount);
    sendRequest.changeAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.emptyWallet = amount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            if (bluetoothAdapter != null && bluetoothAdapter.isEnabled() && bluetoothMac != null
                    && bluetoothEnableView.isChecked()) {
                new SendBluetoothTask(bluetoothAdapter, backgroundHandler) {
                    @Override
                    protected void onResult(final boolean ack) {
                        bluetoothAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }
                }.send(bluetoothMac, transaction); // send asynchronously
            }

            application.broadcastTransaction(sentTransaction);

            final Intent result = new Intent();
            BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
            activity.setResult(Activity.RESULT_OK, result);
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpInterfaceEventListener.java

@Override
protected void add(InstanceIdentifier<Interface> identifier, Interface add) {
    String interfaceName = add.getName();
    List<String> ofportIds = add.getLowerLayerIf();
    if (ofportIds == null || ofportIds.isEmpty()) {
        return;/*ww  w  .jav a 2s .  co  m*/
    }
    NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
    BigInteger dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
    logger.trace("Received add DCN for interface {}, dpid {}", interfaceName, dpId);
    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface = DhcpServiceUtils
            .getInterfaceFromConfigDS(add.getName(), dataBroker);
    if (iface != null) {
        IfTunnel tunnelInterface = iface.getAugmentation(IfTunnel.class);
        if (tunnelInterface != null && !tunnelInterface.isInternal()) {
            IpAddress tunnelIp = tunnelInterface.getTunnelDestination();
            List<BigInteger> dpns = DhcpServiceUtils.getListOfDpns(dataBroker);
            if (dpns.contains(dpId)) {
                dhcpExternalTunnelManager.handleTunnelStateUp(tunnelIp, dpId);
                dhcpManager.bindDhcpService(interfaceName, NwConstants.DHCP_TABLE_EXTERNAL_TUNNEL);
            }
            return;
        }
    }
    if (!dpId.equals(DHCPMConstants.INVALID_DPID)) {
        Port port = dhcpManager.getNeutronPort(interfaceName);
        Subnet subnet = dhcpManager.getNeutronSubnet(port);
        if (null != subnet && subnet.isEnableDhcp()) {
            logger.info("DhcpInterfaceEventListener add isEnableDhcp" + subnet.isEnableDhcp());
            installDhcpEntries(interfaceName, dpId);
            dhcpManager.updateInterfaceCache(interfaceName,
                    new ImmutablePair<>(dpId, add.getPhysAddress().getValue()));
        }
    }
}

From source file:ja.keystore00.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*from  www.j  ava2 s.co m*/
    updateView();

    // create spend
    final BigInteger amount = amountCalculatorLink.getAmount();
    final SendRequest sendRequest = SendRequest.to(validatedAddress.address, amount);
    sendRequest.changeAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.emptyWallet = amount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            if (bluetoothAdapter != null && bluetoothAdapter.isEnabled() && bluetoothMac != null
                    && bluetoothEnableView.isChecked()) {
                new SendBluetoothTask(bluetoothAdapter, backgroundHandler) {
                    @Override
                    protected void onResult(final boolean ack) {
                        bluetoothAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }
                }.send(bluetoothMac, transaction); // send asynchronously
            }

            application.broadcastTransaction(sentTransaction);

            final Intent result = new Intent();
            BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
            activity.setResult(Activity.RESULT_OK, result);
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateView();
                    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
                    bld.setTitle(R.string.send_coins_error_msg);
                    bld.setMessage(R.string.send_coins_error_desc);
                    bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
                    bld.setCancelable(false);
                    bld.create().show();
                }
            });
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:ja.ohac.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*from  w  w  w . j  a  v a  2  s . co m*/
    updateView();

    // create spend
    final BigInteger amount = amountCalculatorLink.getAmount();
    final SendRequest sendRequest = SendRequest.to(validatedAddress.address, amount);
    sendRequest.changeAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.emptyWallet = amount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 DOGE can't be possible due to min fee 2 DOGE of such a tx.
    if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet) {
        AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
        state = State.FAILED;
        updateView();
        return;
    }

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            if (bluetoothAdapter != null && bluetoothAdapter.isEnabled() && bluetoothMac != null
                    && bluetoothEnableView.isChecked()) {
                new SendBluetoothTask(bluetoothAdapter, backgroundHandler) {
                    @Override
                    protected void onResult(final boolean ack) {
                        bluetoothAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }
                }.send(bluetoothMac, transaction); // send asynchronously
            }

            application.broadcastTransaction(sentTransaction);

            final Intent result = new Intent();
            BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
            activity.setResult(Activity.RESULT_OK, result);
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateView();
                    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
                    bld.setTitle(R.string.send_coins_error_msg);
                    bld.setMessage(R.string.send_coins_error_desc);
                    bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
                    bld.setCancelable(false);
                    bld.create().show();
                }
            });
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);// ww  w. ja  va  2 s  . c  om
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.eclipse.om2m.core.controller.Controller.java

/**
 * Checks the Access Right based on ACP list (Permission)
 * @param acp - Id of the accessRight// w  w  w  .j a va  2s  .  co m
 * @param originator - requesting entity used by the requester
 * @param operation - requested method
 * @return error with a specific status code if the requesting Entity or the method does not exist otherwise null
 */
public void checkACP(List<AccessControlPolicyEntity> acpList, String originator, BigInteger operation)
        throws AccessDeniedException {
    if (originator == null) {
        throw new AccessDeniedException();
    }
    if (acpList == null || acpList.isEmpty()) {
        throw new ResourceNotFoundException("Current resource does not have any ACP attached");
    }
    // Check Resource accessRight existence not found
    boolean originatorFound = false;
    boolean operationAllowed = false;
    for (AccessControlPolicyEntity acp : acpList) {
        for (AccessControlRuleEntity rule : acp.getPrivileges()) {
            originatorFound = false;
            operationAllowed = false;
            for (AccessControlOriginatorEntity originatorEntity : rule.getAccessControlOriginators()) {
                if (originator.matches(originatorEntity.getOriginatorID().replace("*", ".*"))) {
                    originatorFound = true;
                    break;
                }
            }
            if (originatorFound) {
                if (operation.equals(Operation.CREATE) && rule.isCreate()) {
                    operationAllowed = true;
                } else if (operation.equals(Operation.RETRIEVE) && rule.isRetrieve()) {
                    operationAllowed = true;
                } else if (operation.equals(Operation.UPDATE) && rule.isUpdate()) {
                    operationAllowed = true;
                } else if (operation.equals(Operation.DELETE) && rule.isDelete()) {
                    operationAllowed = true;
                } else if (operation.equals(Operation.DISCOVERY) && rule.isDiscovery()) {
                    operationAllowed = true;
                } else if (operation.equals(Operation.NOTIFY) && rule.isNotify()) {
                    operationAllowed = true;
                }
            }
            if (originatorFound && operationAllowed) {
                break;
            }
        }
        if (originatorFound && operationAllowed) {
            break;
        }
    }

    if (!originatorFound) {
        throw new AccessDeniedException();
    }
    if (!operationAllowed) {
        throw new AccessDeniedException();
    }
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) {

    LOG.debug("CRL URI: " + crlUri);
    X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate);
    if (null == x509crl) {
        return null;
    }//ww  w . ja  v a  2 s  .co  m

    // check CRL integrity
    boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate);
    if (false == crlIntegrityResult) {
        return null;
    }

    // check CRL signature
    TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName());
    if (!trustResult.isValid()) {
        return trustResult;
    }

    // we don't support indirect CRLs
    if (isIndirectCRL(x509crl)) {
        LOG.debug("indirect CRL detected");
        return null;
    }

    LOG.debug("CRL number: " + getCrlNumber(x509crl));
    // check delta CRL indicator against completeCrlNuber
    if (null != baseCrlNumber) {
        BigInteger crlNumber = getDeltaCrlIndicator(x509crl);
        if (!baseCrlNumber.equals(crlNumber)) {
            LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber
                    + ")");
            return null;
        }
    }

    // fill up revocation data if not null with this valid CRL
    if (null != revocationData) {
        try {
            revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded()));
        } catch (CRLException e) {
            LOG.error("CRLException: " + e.getMessage(), e);
            throw new RuntimeException("CRLException : " + e.getMessage(), e);
        }
    }

    boolean revoked = true;
    X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber());
    if (null == crlEntry) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal());
        revoked = false;
    } else if (crlEntry.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        revoked = false;
    }

    if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) {
        // Delta CRL
        if (!revoked)
            return null;

    } else {
        // Base CRL, look for delta's
        List<URI> deltaCrlUris = getDeltaCrlUris(x509crl);
        if (null != deltaCrlUris) {
            for (URI deltaCrlUri : deltaCrlUris) {
                LOG.debug("delta CRL: " + deltaCrlUri.toString());
                TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate,
                        validationDate, revocationData, getCrlNumber(x509crl));
                if (null != result)
                    return result;
            }
        }
    }

    if (!revoked)
        return new TrustLinkerResult(true);

    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by CRL=" + crlEntry.getSerialNumber());

}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the user associated to a certiciate in LDAP server
 * @param x509Certificate/*from ww  w . ja va  2  s  . c om*/
 * @return the user of the certificate or null if no associate exist
 */
public User getUserByCertificate(X509Certificate x509Certificate) {

    if (logger.isInfoEnabled()) {
        logger.info("Get user for serial number " + x509Certificate.getSerialNumber().toString(16));
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter("userCertificate", "*"));
    for (String rdn : rdnUsers) {
        List serialNumbers = ldapTemplate.search(rdn, filterS.encode(), new AbstractContextMapper() {
            public Object doMapFromContext(DirContextOperations ctx) {

                try {
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(
                            new ByteArrayInputStream((byte[]) ctx.getObjectAttribute(CERTIFICATE_ATTRIBUTE)));

                    if (ctx.getStringAttribute(MAIL_ATTRIBUTE) == null)
                        ctx.setAttributeValue(MAIL_ATTRIBUTE, "");
                    if (ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE) == null)
                        ctx.setAttributeValue(COMMON_NAME_ATTRIBUTE, "");

                    String uid = ctx.getStringAttribute(UID_ATTRIBUTE);

                    //get the date of last modify of this user
                    LdapTemplate tmp = new LdapTemplate();
                    tmp.setContextSource(ldapContextSource);
                    final String[] attrOp = { MODIFY_TIMESTAMP_ATTRIBUTE };
                    Object o = tmp.lookup(ctx.getDn(), attrOp, new ContextMapper() {
                        public Object mapFromContext(Object ctx) {
                            DirContextAdapter adapter = (DirContextAdapter) ctx;
                            return adapter.getStringAttribute(attrOp[0]);

                        }
                    }

                    );

                    Date lastPasswordChange; //the time of last change for the entry
                    if (o != null) {
                        String modifyTimestamp = o.toString();
                        lastPasswordChange = getDate(modifyTimestamp);
                    } else {
                        //if the modifyTimeStamp is null
                        lastPasswordChange = new Date();
                    }

                    LdapUser user = new LdapUser(uid, ctx.getNameInNamespace(),
                            ctx.getStringAttribute(MAIL_ATTRIBUTE),
                            ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE), lastPasswordChange, getRealm());

                    Object[] tab = { x509Certificate.getSerialNumber(), user };

                    return tab;

                } catch (Exception e) {

                    logger.error(e);
                    return null;
                }
            }
        });

        if (serialNumbers != null) {
            for (Object o : serialNumbers) {

                Object[] tab = (Object[]) o;
                BigInteger serialNumber = (BigInteger) tab[0];
                LdapUser user = (LdapUser) tab[1];
                if (serialNumber.equals(x509Certificate.getSerialNumber()))
                    return user;
            }
        }
    }

    return null;

}

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

private void deleteAllRemoteMacsInADpn(String elanName, BigInteger dpId, long elanTag) {
    List<DpnInterfaces> dpnInterfaces = ElanUtils.getInvolvedDpnsInElan(elanName);
    for (DpnInterfaces dpnInterface : dpnInterfaces) {
        BigInteger currentDpId = dpnInterface.getDpId();
        if (!currentDpId.equals(dpId)) {
            for (String elanInterface : dpnInterface.getInterfaces()) {
                ElanInterfaceMac macs = ElanUtils.getElanInterfaceMacByInterfaceName(elanInterface);
                if (macs == null) {
                    continue;
                }//from w w  w .  j av  a 2s.c o m
                for (MacEntry mac : macs.getMacEntry())
                    mdsalManager.removeFlow(dpId,
                            MDSALUtil.buildFlow(ElanConstants.ELAN_DMAC_TABLE,
                                    ElanUtils.getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId,
                                            currentDpId, mac.getMacAddress().getValue(), elanTag)));
            }
        }
    }
}

From source file:org.cesecore.certificates.util.AlgorithmTools.java

/**
 * Gets the key specification from a public key. Example: "2048" for a RSA 
 * or DSA key or "secp256r1" for EC key. The EC curve is only detected 
 * if <i>publickey</i> is an object known by the bouncy castle provider.
 * @param publicKey The public key to get the key specification from
 * @return The key specification, "unknown" if it could not be determined and
 * null if the key algorithm is not supported
 *//*from  w  w  w .java  2 s.  com*/
public static String getKeySpecification(final PublicKey publicKey) {
    if (log.isTraceEnabled()) {
        log.trace(">getKeySpecification");
    }
    String keyspec = null;
    if (publicKey instanceof RSAPublicKey) {
        keyspec = Integer.toString(((RSAPublicKey) publicKey).getModulus().bitLength());
    } else if (publicKey instanceof DSAPublicKey) {
        keyspec = Integer.toString(((DSAPublicKey) publicKey).getParams().getP().bitLength());
    } else if (publicKey instanceof ECPublicKey) {
        final ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        if (ecPublicKey.getParams() instanceof ECNamedCurveSpec) {
            keyspec = ((ECNamedCurveSpec) ecPublicKey.getParams()).getName();
            // Prefer to return a curve name alias that also works with the default and BC provider
            for (String keySpecAlias : getEcKeySpecAliases(keyspec)) {
                if (isNamedECKnownInDefaultProvider(keySpecAlias)) {
                    keyspec = keySpecAlias;
                    break;
                }
            }
        } else {
            keyspec = KEYSPEC_UNKNOWN;
            // Try to detect if it is a curve name known by BC even though the public key isn't a BC key
            final ECParameterSpec namedCurve = ecPublicKey.getParams();
            if (namedCurve != null) {
                final int c1 = namedCurve.getCofactor();
                final EllipticCurve ec1 = namedCurve.getCurve();
                final BigInteger a1 = ec1.getA();
                final BigInteger b1 = ec1.getB();
                final int fs1 = ec1.getField().getFieldSize();
                //final byte[] s1 = ec1.getSeed();
                final ECPoint g1 = namedCurve.getGenerator();
                final BigInteger ax1 = g1.getAffineX();
                final BigInteger ay1 = g1.getAffineY();
                final BigInteger o1 = namedCurve.getOrder();
                if (log.isDebugEnabled()) {
                    log.debug("a1=" + a1 + " b1=" + b1 + " fs1=" + fs1 + " ax1=" + ax1 + " ay1=" + ay1 + " o1="
                            + o1 + " c1=" + c1);
                }
                @SuppressWarnings("unchecked")
                final Enumeration<String> ecNamedCurves = ECNamedCurveTable.getNames();
                while (ecNamedCurves.hasMoreElements()) {
                    final String ecNamedCurveBc = ecNamedCurves.nextElement();
                    final ECNamedCurveParameterSpec parameterSpec2 = ECNamedCurveTable
                            .getParameterSpec(ecNamedCurveBc);
                    final ECCurve ec2 = parameterSpec2.getCurve();
                    final BigInteger a2 = ec2.getA().toBigInteger();
                    final BigInteger b2 = ec2.getB().toBigInteger();
                    final int fs2 = ec2.getFieldSize();
                    final org.bouncycastle.math.ec.ECPoint g2 = parameterSpec2.getG();
                    final BigInteger ax2 = g2.getX().toBigInteger();
                    final BigInteger ay2 = g2.getY().toBigInteger();
                    final BigInteger h2 = parameterSpec2.getH();
                    final BigInteger n2 = parameterSpec2.getN();
                    if (a1.equals(a2) && ax1.equals(ax2) && b1.equals(b2) && ay1.equals(ay2) && fs1 == fs2
                            && o1.equals(n2) && c1 == h2.intValue()) {
                        // We have a matching curve here!
                        if (log.isDebugEnabled()) {
                            log.debug("a2=" + a2 + " b2=" + b2 + " fs2=" + fs2 + " ax2=" + ax2 + " ay2=" + ay2
                                    + " h2=" + h2 + " n2=" + n2 + " " + ecNamedCurveBc);
                        }
                        // Since this public key is a SUN PKCS#11 pub key if we get here, we only return an alias if it is recognized by the provider
                        if (isNamedECKnownInDefaultProvider(ecNamedCurveBc)) {
                            keyspec = ecNamedCurveBc;
                            break;
                        }
                    }
                }
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getKeySpecification: " + keyspec);
    }
    return keyspec;
}