Example usage for java.security NoSuchAlgorithmException getMessage

List of usage examples for java.security NoSuchAlgorithmException getMessage

Introduction

In this page you can find the example usage for java.security NoSuchAlgorithmException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.sling.cassandra.resource.provider.CassandraResourceProvider.java

private boolean insertResource(String path, Map map) throws PersistenceException {
    try {//from ww  w.  j a  v  a2s.c o  m
        String r = getrowID(path);
        if (r == null) {
            return false;
        }
        String _cf = CassandraResourceProviderUtil.getColumnFamilySector(path);
        createColumnFamily(_cf, this.getKeyspace(), new StringSerializer());
        String metadata = map.get("metadata") == null ? "resolutionPathInfo=json"
                : (String) map.get("metadata");
        String resourceType = map.get("resourceType") == null ? "nt:cassandra"
                : (String) map.get("resourceType");
        String resourceSuperType = map.get("resourceSuperType") == null ? "nt:superCassandra"
                : (String) map.get("resourceSuperType");

        addData(this.getKeyspace(), _cf, new StringSerializer(), new String[] { "'" + r + "','" + path + "','"
                + resourceType + "','" + resourceSuperType + "','" + metadata + "'", });
    } catch (NoSuchAlgorithmException e) {
        throw new PersistenceException(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw new PersistenceException(e.getMessage());
    }
    return true;
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This finds a <code>KeyGenerator</code> using the known providers and the
 * supplied algorithm parameter.</p>
 *
 * @param  algorithm  <code>String</code> name
 *
 * @return  <code>KeyGenerator</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 */// w w w.  j a  va 2s.  co m
public static KeyGenerator getKeyGenerator(final String algorithm) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    KeyGenerator generator = null;
    for (int i = 0; i < providers.length; i++) {
        try {
            generator = KeyGenerator.getInstance(algorithm, providers[i]);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (generator != null) {
                break;
            }
        }
    }
    if (generator == null) {
        try {
            generator = KeyGenerator.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return generator;
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies a non-repudiation signature.
 * /*from   w  w  w  .j a  v a  2 s . co m*/
 * @param expectedDigestValue
 * @param signatureValue
 * @param certificate
 * @return
 */
public boolean verifyNonRepSignature(final byte[] expectedDigestValue, final byte[] signatureValue,
        final X509Certificate certificate) {
    try {
        return __verifyNonRepSignature(expectedDigestValue, signatureValue, certificate);
    } catch (final InvalidKeyException ikex) {
        LOG.warn("invalid key: " + ikex.getMessage(), ikex);
        return false;
    } catch (final NoSuchAlgorithmException nsaex) {
        LOG.warn("no such algo: " + nsaex.getMessage(), nsaex);
        return false;
    } catch (final NoSuchPaddingException nspex) {
        LOG.warn("no such padding: " + nspex.getMessage(), nspex);
        return false;
    } catch (final BadPaddingException bpex) {
        LOG.warn("bad padding: " + bpex.getMessage(), bpex);
        return false;
    } catch (final IOException ioex) {
        LOG.warn("IO error: " + ioex.getMessage(), ioex);
        return false;
    } catch (final IllegalBlockSizeException ibex) {
        LOG.warn("illegal block size: " + ibex.getMessage(), ibex);
        return false;
    }
}

From source file:org.rhq.modules.plugins.jbossas7.BaseServerComponent.java

protected OperationResult installManagementUser(Configuration parameters, Configuration pluginConfig,
        AS7Mode mode) {/*from  w  w  w.  j  ava  2s.  c om*/
    String user = parameters.getSimpleValue("user", "");
    String password = parameters.getSimpleValue("password", "");

    OperationResult result = new OperationResult();

    PropertySimple remoteProp = pluginConfig.getSimple("manuallyAdded");
    if (remoteProp != null && remoteProp.getBooleanValue() != null && remoteProp.getBooleanValue()) {
        result.setErrorMessage(
                "This is a manually added server. This operation can not be used to install a management user. Use the server's 'bin/add-user.sh'");
        return result;
    }

    if (user.isEmpty() || password.isEmpty()) {
        result.setErrorMessage("User and Password must not be empty");
        return result;
    }

    String baseDir = pluginConfig.getSimpleValue("baseDir", "");
    if (baseDir.isEmpty()) {
        result.setErrorMessage("No baseDir found, can not continue");
        return result;
    }
    String standaloneXmlFile = pluginConfig.getSimpleValue("config", mode.getDefaultXmlFile());

    String standaloneXml = baseDir + File.separator + mode.getBaseDir() + File.separator + "configuration"
            + File.separator + standaloneXmlFile;

    AbstractBaseDiscovery abd = new AbstractBaseDiscovery();
    abd.readStandaloneOrHostXmlFromFile(standaloneXml);

    String realm = pluginConfig.getSimpleValue("realm", "ManagementRealm");
    String propertiesFilePath = abd.getSecurityPropertyFileFromHostXml(baseDir, mode, realm);

    Properties p = new Properties();
    try {
        UsernamePasswordHashUtil util = new UsernamePasswordHashUtil();
        String value = util.generateHashedHexURP(user, realm, password.toCharArray());

        FileInputStream fis = new FileInputStream(propertiesFilePath);
        p.load(fis);
        fis.close();
        p.setProperty(user, value);
        FileOutputStream fos = new FileOutputStream(propertiesFilePath);
        p.store(fos, null);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        log.error(e.getMessage());
        result.setErrorMessage(e.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        log.error(nsae.getMessage());
        result.setErrorMessage(nsae.getMessage());
    }
    result.setSimpleResult("User/Password set or updated");
    log.info("Installed management user [" + user + "].");

    return result;
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This finds a <code>KeyPairGenerator</code> using the known providers and
 * the supplied algorithm parameter.</p>
 *
 * @param  algorithm  <code>String</code> name
 *
 * @return  <code>KeyPairGenerator</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 *//*  w w w. j  a va 2s  . c om*/
public static KeyPairGenerator getKeyPairGenerator(final String algorithm) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    KeyPairGenerator generator = null;
    for (int i = 0; i < providers.length; i++) {
        try {
            generator = KeyPairGenerator.getInstance(algorithm, providers[i]);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (generator != null) {
                break;
            }
        }
    }
    if (generator == null) {
        try {
            generator = KeyPairGenerator.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return generator;
}

From source file:edu.wpi.checksims.algorithm.linesimilarity.LineSimilarityChecker.java

/**
 * Detect similarities using line similarity comparator.
 *
 * @param a First submission to check/*from   w w w .j  a  v  a  2s  . c  o  m*/
 * @param b Second submission to check
 * @return Results of the similarity detection
 * @throws TokenTypeMismatchException Thrown comparing two submissions with different token types
 * @throws InternalAlgorithmError Thrown on error obtaining a hash algorithm instance
 */
@Override
public AlgorithmResults detectSimilarity(Submission a, Submission b)
        throws TokenTypeMismatchException, InternalAlgorithmError {
    checkNotNull(a);
    checkNotNull(b);

    TokenList linesA = a.getContentAsTokens();
    TokenList linesB = b.getContentAsTokens();
    TokenList finalA = TokenList.cloneTokenList(linesA);
    TokenList finalB = TokenList.cloneTokenList(linesB);

    if (!a.getTokenType().equals(b.getTokenType())) {
        throw new TokenTypeMismatchException(
                "Token list type mismatch: submission " + a.getName() + " has type " + linesA.type.toString()
                        + ", while submission " + b.getName() + " has type " + linesB.type.toString());
    } else if (a.equals(b)) {
        finalA.stream().forEach((token) -> token.setValid(false));
        finalB.stream().forEach((token) -> token.setValid(false));
        return new AlgorithmResults(a, b, finalA, finalB);
    }

    MessageDigest hasher;

    // Get a hashing instance
    try {
        hasher = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
        throw new InternalAlgorithmError("Error instantiating SHA-512 hash algorithm: " + e.getMessage());
    }

    // Create a line database map
    // Per-method basis to ensure we have no mutable state in the class
    Map<String, List<SubmissionLine>> lineDatabase = new HashMap<>();

    // Hash all lines in A, and put them in the lines database
    addLinesToMap(linesA, lineDatabase, a, hasher);

    // Hash all lines in B, and put them in the lines database
    addLinesToMap(linesB, lineDatabase, b, hasher);

    // Number of matched lines contained in both
    int identicalLinesA = 0;
    int identicalLinesB = 0;

    // Check all the keys
    for (String key : lineDatabase.keySet()) {

        // If more than 1 line has the hash...
        if (lineDatabase.get(key).size() != 1) {
            int numLinesA = 0;
            int numLinesB = 0;

            // Count the number of that line in each submission
            for (SubmissionLine s : lineDatabase.get(key)) {
                if (s.submission.equals(a)) {
                    numLinesA++;
                } else if (s.submission.equals(b)) {
                    numLinesB++;
                } else {
                    throw new RuntimeException("Unreachable code!");
                }
            }

            if (numLinesA == 0 || numLinesB == 0) {
                // Only one of the submissions includes the line - no plagiarism here
                continue;
            }

            // Set matches invalid
            for (SubmissionLine s : lineDatabase.get(key)) {
                if (s.submission.equals(a)) {
                    finalA.get(s.lineNum).setValid(false);
                } else if (s.submission.equals(b)) {
                    finalB.get(s.lineNum).setValid(false);
                } else {
                    throw new RuntimeException("Unreachable code!");
                }
            }

            identicalLinesA += numLinesA;
            identicalLinesB += numLinesB;
        }
    }

    int invalTokensA = (int) finalA.stream().filter((token) -> !token.isValid()).count();
    int invalTokensB = (int) finalB.stream().filter((token) -> !token.isValid()).count();

    if (invalTokensA != identicalLinesA) {
        throw new InternalAlgorithmError("Internal error: number of identical tokens (" + identicalLinesA
                + ") does not match number of invalid tokens (" + invalTokensA + ")");
    } else if (invalTokensB != identicalLinesB) {
        throw new InternalAlgorithmError("Internal error: number of identical tokens (" + identicalLinesB
                + ") does not match number of invalid tokens (" + invalTokensB + ")");
    }

    return new AlgorithmResults(a, b, finalA, finalB);
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

private SSLContext createSSLContext() {
    try {// w ww  .j  av a  2  s  . co m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;

        if (this.keyStoreUrl != null) {
            KeyStore keystore = createStore(this.keyStoreUrl, this.keyStorePassword, this.keyStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        log.debug("Certificate chain '{}':", alias);
                        for (int i = 0; i < certs.length; ++i) {
                            if (certs[i] instanceof X509Certificate) {
                                log.debug(" Certificate {}:", i + 1);
                                logCertificate((X509Certificate) certs[i]);
                            }
                        }
                    }
                }
            }

            keymanagers = createKeyManagers(keystore, this.keyStorePassword);
        }

        if (this.trustStoreUrl != null) {
            KeyStore keystore = createStore(this.trustStoreUrl, this.trustStorePassword, this.trustStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    log.debug("Trusted certificate '{}':", alias);
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert instanceof X509Certificate) {
                        logCertificate((X509Certificate) trustedcert);
                    }
                }
            }

            trustmanagers = createTrustManagers(keystore);
        }

        SSLContext context = SSLContext.getInstance("SSL");
        context.init(keymanagers, trustmanagers, null);

        return context;
    } catch (NoSuchAlgorithmException e) {
        throw new LtSSLInitializationException("Unsupported algorithm exception: " + e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new LtSSLInitializationException("Keystore exception: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new LtSSLInitializationException("Key management exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new LtSSLInitializationException(
                "I/O error reading key store/trust store file: " + e.getMessage(), e);
    }
}

From source file:org.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

/**
 * Calculates a checksum for the supplied resource, using the supplied algorithm.
 *
 * @param algo the algorithm// www .j  a v a 2s .c om
 * @param r the resource
 * @return the byte representation of the checksum
 * @throws RuntimeException if the checksum cannot be calculated for whatever reason
 */
private byte[] calculateChecksum(String algo, Resource r) {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    InputStream in = null;
    try {
        in = r.getInputStream();
    } catch (Exception e) {
        throw new RuntimeException(
                "Unable to obtain inputstream for Resource " + r.getFilename() + ": " + e.getMessage(), e);
    }
    int read = 0;
    int size = 1024;
    byte[] buf = new byte[size];
    try {
        while ((read = in.read(buf, 0, size)) != -1) {
            md.update(buf, 0, read);
        }
    } catch (IOException e) {
        throw new RuntimeException(
                "Unable to calculate checksum for Resource " + r.getFilename() + ": " + e.getMessage(), e);
    }

    return md.digest();
}

From source file:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java

/**
 * Throws an error if state parameter is not the expected one.
 * //from   ww w.  j av  a2s  . co m
 * @param httpRequest
 *            is the httpRequest we check for state.
 * @throws SocialUserAuthenticationException
 *             if the parameter is missing or mismatches.
 * */
private void validateState(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    String state = httpRequest.getParameter("state");
    if (state == null) {
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter missing", SocialUserErrorIds.EXCEPTION);
    }
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate state");
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("Unable to hash, use some other method",
                SocialUserErrorIds.EXCEPTION);
    }
    md.reset();
    md.update(httpRequest.getSession().getId().getBytes());
    String cmpState = new String(Hex.encode(md.digest()));
    if (!state.equalsIgnoreCase(cmpState)) {
        log.error("state parameter mismatch");
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter mismatch", SocialUserErrorIds.EXCEPTION);
    }
}

From source file:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java

/**
 * Returns redirect url for authentication.
 * //from www  .  j a v a 2  s  . c o  m
 * @param httpRequest
 *            the request
 * 
 * @return redirect url
 */
public String getRedirectUrl(HttpServletRequest httpRequest) {
    log.trace("Entering");
    if (httpRequest == null) {
        log.trace("Leaving");
        return null;
    }
    OAuth2Parameters params = new OAuth2Parameters();
    if (scope != null) {
        params.setScope(scope);
    }
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.reset();
        md.update(httpRequest.getSession().getId().getBytes());
        String digest = new String(Hex.encode(md.digest()));
        params.setState(digest);
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate state");
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        return null;
    }
    params.setRedirectUri(httpRequest.getRequestURL().toString());
    String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
    log.trace("Leaving");
    return authorizeUrl;

}