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.ckan.Connection.java

/**
* Makes a POST request/*ww w  . j a v a2 s.  c o  m*/
*
* Submits a POST HTTP request to the CKAN instance configured within
* the constructor, returning the entire contents of the response.
*
* @param  path The URL path to make the POST request to
* @param  data The data to be posted to the URL
* @returns The String contents of the response
* @throws A CKANException if the request fails
*/
protected String post(String path, String data) throws CKANException {
    URL url = null;

    try {
        url = new URL(this.m_host + ":" + this.m_port + path);
    } catch (MalformedURLException mue) {
        System.err.println(mue);
        return null;
    }

    String body = "";

    BasicClientConnectionManager bccm = null;
    ClientConnectionManager cm = null;
    try {
        /***********************************************************************/
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        //bccm = new BasicClientConnectionManager(schemeRegistry);
        // apache HttpClient version >4.2 should use BasicClientConnectionManager
        cm = new SingleClientConnManager(schemeRegistry);
        /***********************************************************************/
    } catch (KeyManagementException kme) {
        System.out.println("Con ex: " + kme.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        System.out.println("Con ex: " + nsae.getMessage());
    }

    //HttpClient httpclient = new DefaultHttpClient(cm);
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost postRequest = new HttpPost(url.toString());
        postRequest.setHeader("X-CKAN-API-Key", this._apikey);

        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpclient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String line = "";
        while ((line = br.readLine()) != null) {
            body += line;
        }
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return body;
}

From source file:org.atombeat.xquery.functions.util.StreamRequestDataToFile.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    logger.debug("begin stream request data to file eval");

    logger.debug("access request module from context");
    RequestModule reqModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);

    // request object is read from global variable $request
    Variable var = reqModule.resolveVariable(RequestModule.REQUEST_VAR);

    if (var == null || var.getValue() == null)
        throw new XPathException(this, "No request object found in the current XQuery context.");

    if (var.getValue().getItemType() != Type.JAVA_OBJECT)
        throw new XPathException(this, "Variable $request is not bound to an Java object.");

    JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);

    if (!(value.getObject() instanceof RequestWrapper)) {
        throw new XPathException(this, "Variable $request is not bound to a Request object.");
    }// w  w  w. j  a  va  2s. c om

    logger.debug("access wrapped request");
    RequestWrapper request = (RequestWrapper) value.getObject();

    // we have to access the content-length header directly, rather than do request.getContentLength(), in case it's bigger than an int
    String contentLengthHeader = request.getHeader("Content-Length");

    if (contentLengthHeader == null) {
        logger.debug("content length header is null, returning empty sequence");
        return Sequence.EMPTY_SEQUENCE;
    }

    long contentLength = Long.parseLong(contentLengthHeader);
    logger.debug("content length via header: " + contentLength);
    logger.debug("request.getContentLength(): " + request.getContentLength()); // will be -1 if value is greater than an int

    // try to stream request content to file
    try {
        logger.debug("try to stream request data to file...");
        logger.debug("open request input stream");
        InputStream in = request.getInputStream();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        logger.debug("create digest input stream");
        in = new DigestInputStream(in, md5);
        String path = args[0].getStringValue();
        logger.debug("creating file at path: " + path);
        File file = new File(path);
        logger.debug("creating file output stream");
        FileOutputStream out = new FileOutputStream(file);
        logger.debug("begin streaming data");
        Stream.copy(in, out, contentLength);
        logger.debug("end streaming data");
        logger.debug("create md5 signature");
        String signature = new BigInteger(1, md5.digest()).toString(16);
        logger.debug("return signature");
        return new StringValue(signature);

    } catch (IOException ioe) {
        throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(this, "A message digest exception ocurred: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new XPathException(this, "An unexpected exception ocurred: " + e.getMessage(), e);
    }

}

From source file:org.openhab.binding.km200.internal.KM200Cryption.java

/**
 * This function creates the private key from the MD5Salt, the device and the private password
 *
 * @author Markus Eckhardt/*from w w  w .j a v  a  2 s.  c om*/
 */
public void recreateKeys() {
    if (StringUtils.isNotBlank(remoteDevice.getGatewayPassword())
            && StringUtils.isNotBlank(remoteDevice.getPrivatePassword()) && remoteDevice.getMD5Salt() != null) {
        byte[] md5K1 = null;
        byte[] md5K2Init = null;
        byte[] md5K2Private = null;
        byte[] bytesOfGatewayPassword = null;
        byte[] bytesOfPrivatePassword = null;

        /* Needed keys for the communication */
        byte[] cryptKeyInit;
        byte[] cryptKeyPriv;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("No such algorithm, MD5: {}", e.getMessage());
            return;
        }

        /* First half of the key: MD5 of (GatewayPassword . Salt) */
        bytesOfGatewayPassword = remoteDevice.getGatewayPassword().getBytes(StandardCharsets.UTF_8);
        byte[] combParts1 = new byte[bytesOfGatewayPassword.length + remoteDevice.getMD5Salt().length];
        System.arraycopy(bytesOfGatewayPassword, 0, combParts1, 0, bytesOfGatewayPassword.length);
        System.arraycopy(remoteDevice.getMD5Salt(), 0, combParts1, bytesOfGatewayPassword.length,
                remoteDevice.getMD5Salt().length);
        md5K1 = md.digest(combParts1);

        /* Second half of the key: - Initial: MD5 of ( Salt) */
        md5K2Init = md.digest(remoteDevice.getMD5Salt());

        /* Second half of the key: - private: MD5 of ( Salt . PrivatePassword) */
        bytesOfPrivatePassword = remoteDevice.getPrivatePassword().getBytes(StandardCharsets.UTF_8);
        byte[] combParts2 = new byte[bytesOfPrivatePassword.length + remoteDevice.getMD5Salt().length];
        System.arraycopy(remoteDevice.getMD5Salt(), 0, combParts2, 0, remoteDevice.getMD5Salt().length);
        System.arraycopy(bytesOfPrivatePassword, 0, combParts2, remoteDevice.getMD5Salt().length,
                bytesOfPrivatePassword.length);
        md5K2Private = md.digest(combParts2);

        /* Create Keys */
        cryptKeyInit = new byte[md5K1.length + md5K2Init.length];
        System.arraycopy(md5K1, 0, cryptKeyInit, 0, md5K1.length);
        System.arraycopy(md5K2Init, 0, cryptKeyInit, md5K1.length, md5K2Init.length);
        remoteDevice.setCryptKeyInit(cryptKeyInit);

        cryptKeyPriv = new byte[md5K1.length + md5K2Private.length];
        System.arraycopy(md5K1, 0, cryptKeyPriv, 0, md5K1.length);
        System.arraycopy(md5K2Private, 0, cryptKeyPriv, md5K1.length, md5K2Private.length);
        remoteDevice.setCryptKeyPriv(cryptKeyPriv);
    }
}

From source file:org.dspace.eperson.PasswordHash.java

/**
 * Is this the string whose hash I hold?
 *
 * @param secret string to be hashed and compared to this hash.
 * @return true if secret hashes to the value held by this instance.
 *///w  w  w  .ja  v a 2s .  c  o  m
public boolean matches(String secret) {
    byte[] candidate;
    try {
        candidate = digest(salt, algorithm, secret);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage());
        return false;
    }
    return Arrays.equals(candidate, hash);
}

From source file:org.opencastproject.kernel.http.impl.HttpClientImpl.java

/**
 * Creates a new client that can deal with all kinds of oddities with regards to http/https connections.
 * //  www  .j a  va  2s .  c o m
 * @return the client
 */
private DefaultHttpClient makeHttpClient() {

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    try {
        logger.debug("Installing forgiving hostname verifier and trust managers");
        X509TrustManager trustManager = createTrustManager();
        X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
        ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    } catch (KeyManagementException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    }

    return defaultHttpClient;
}

From source file:org.dspace.eperson.PasswordHash.java

/**
 * Construct a hash structure from a cleartext password using the configured
 * digest algorithm./*from  www.ja v a2 s . c om*/
 *
 * @param password the secret to be hashed.
 */
public PasswordHash(String password) {
    // Generate some salt
    salt = generateSalt();

    // What digest algorithm to use?
    algorithm = config.getPropertyAsType(ALGORITHM_PROPERTY, DEFAULT_DIGEST_ALGORITHM);

    // Hash it!
    try {
        hash = digest(salt, algorithm, password);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage());
        hash = new byte[] { 0 };
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public PrivateKey decryptPrivateKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key,
        String keyToDecrypt) throws NetInfCheckedSecurityException {
    try {//from   w  ww  .  ja va 2  s .  c o  m
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.UNWRAP_MODE, key);
        return (PrivateKey) cipher.unwrap(Utils.stringToBytes(keyToDecrypt), algorithmKeyIsUsedFor,
                Cipher.PRIVATE_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public String encryptPrivateKey(String algorithmUsedToEncryptTheKey, Key key, PrivateKey keyToEncrypt)
        throws NetInfCheckedSecurityException {
    try {/*w  w  w.j a v a2s  .c  o  m*/
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.WRAP_MODE, key);
        return Utils.bytesToString(cipher.wrap(keyToEncrypt));
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    } catch (IllegalBlockSizeException e) {
        throw new NetInfCheckedSecurityException("Illegal cipher-block-size: " + e.getMessage());
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public String encryptSecretKey(String algorithmUsedToEncryptTheKey, Key key, SecretKey keyToEncrypt)
        throws NetInfCheckedSecurityException {
    try {/*from  w  w w  .j av a2s  . co m*/
        LOG.debug("Encrypting SecretKey.");
        LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey);
        LOG.trace("Used key: " + key);
        LOG.trace("Used key to be encrypted: " + keyToEncrypt);
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.WRAP_MODE, key);
        return Base64.encodeBase64String(cipher.wrap(keyToEncrypt));
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    } catch (IllegalBlockSizeException e) {
        throw new NetInfCheckedSecurityException("Illegal cipher-block-size: " + e.getMessage());
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public SecretKey decryptSecretKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key,
        String keyToDecrypt) throws NetInfCheckedSecurityException {
    try {// www .  ja v  a 2s.  c  om
        LOG.debug("Decrypting SecretKey.");
        LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey);
        LOG.trace("Used algorithm of encrypted key: " + algorithmKeyIsUsedFor);
        LOG.trace("Used key: " + key);
        LOG.trace("Used key to be decrypted: " + keyToDecrypt);
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.UNWRAP_MODE, key);
        return (SecretKey) cipher.unwrap(Base64.decodeBase64(keyToDecrypt), algorithmKeyIsUsedFor,
                Cipher.SECRET_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    }
}