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.openhealthtools.openexchange.actorconfig.net.SecureSocketFactory.java

private SSLContext createSSLContext() throws IOException {
    try {//w  ww  .j  av a2 s.com
        LOG.info("Attempting to create ssl context.");
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = ConnectionCertificateHandler.createKeyStore(this.keystoreUrl,
                    this.keystorePassword);
            if (LOG.isDebugEnabled())
                ConnectionCertificateHandler.printKeyCertificates(keystore);
            keymanagers = ConnectionCertificateHandler.createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = ConnectionCertificateHandler.createKeyStore(this.truststoreUrl,
                    this.truststorePassword);
            if (LOG.isDebugEnabled())
                ConnectionCertificateHandler.printTrustCerts(keystore);
            trustmanagers = ConnectionCertificateHandler.createTrustManagers(keystore, this.scd);
        }
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error("NSA: " + e.getMessage(), e);
        throw new IOException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error("Key Store: " + e.getMessage(), e);
        throw new IOException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error("General: " + e.getMessage(), e);
        throw new IOException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error("I/O exception: " + e.getMessage(), e);
        throw new IOException("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.whitesource.agent.hash.HashCalculator.java

public String calculateByteArrayHash(byte[] byteArray, HashAlgorithm algorithm) throws IOException {
    MessageDigest messageDigest;//from w  w  w  . ja va2s. c  om
    try {
        messageDigest = MessageDigest.getInstance(algorithm.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    messageDigest.update(byteArray, 0, byteArray.length);
    return toHex(messageDigest.digest());
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String)
 *///from ww w. j  av a  2 s.c o  m
public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#returnKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    KeyPair keyPair = null;
    InputStream pubStream = null;
    InputStream privStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            throw new KeyManagementException("Configured key directory does not exist and unable to create it");
        }

        File publicFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);
        File privateFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

        if ((publicFile.exists()) && (privateFile.exists())) {
            privStream = new FileInputStream(privateFile);
            byte[] privKeyBytes = IOUtils.toByteArray(privStream);

            pubStream = new FileInputStream(publicFile);
            byte[] pubKeyBytes = IOUtils.toByteArray(pubStream);

            // files exist
            KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm());

            // generate private key
            PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes);
            PrivateKey privKey = keyFactory.generatePrivate(privateSpec);

            // generate pubkey
            X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
            PublicKey pubKey = keyFactory.generatePublic(publicSpec);

            // make the keypair
            keyPair = new KeyPair(pubKey, privKey);
        } else {
            // files dont exist
            throw new KeyManagementException("Failed to locate user keys");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeySpecException iksx) {
        throw new KeyManagementException(iksx.getMessage(), iksx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (privStream != null) {
            IOUtils.closeQuietly(privStream);
        }

        if (pubStream != null) {
            IOUtils.closeQuietly(pubStream);
        }
    }

    return keyPair;
}

From source file:com.axibase.tsd.driver.jdbc.protocol.SdkProtocolImpl.java

private void doTrustToCertificates(final HttpsURLConnection sslConnection) {
    final SSLContext sslContext;
    try {//from   w ww.  j  a  v  a2 s  .  c  o m
        sslContext = SSLContext.getInstance(CONTEXT_INSTANCE_TYPE);
    } catch (NoSuchAlgorithmException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    final boolean trusted = contentDescription.isTrusted();
    if (logger.isDebugEnabled()) {
        logger.debug("[doTrustToCertificates] " + trusted);
    }
    try {
        sslContext.init(null, trusted ? DUMMY_TRUST_MANAGER : null, new SecureRandom());
    } catch (KeyManagementException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());

    if (trusted) {
        sslConnection.setHostnameVerifier(DUMMY_HOSTNAME_VERIFIER);
    }
}

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

/**
 * <p>This finds a <code>SecretKeyFactory</code> using the known providers and
 * the supplied algorithm parameter.</p>
 *
 * @param  algorithm  <code>String</code> name
 *
 * @return  <code>SecretKeyFactory</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 *///from   w  w w . ja v a  2 s.  c o  m
public static SecretKeyFactory getSecretKeyFactory(final String algorithm) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    SecretKeyFactory kf = null;
    for (int i = 0; i < providers.length; i++) {
        try {
            kf = SecretKeyFactory.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 (kf != null) {
                break;
            }
        }
    }
    if (kf == null) {
        try {
            kf = SecretKeyFactory.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return kf;
}

From source file:com.CardPaymentGateway.GatewayBillsPayment.java

public void run(String incomingMessage, String intid) {
    try {//from   w w  w  .j a  v  a 2s.c  o  m
        strReceivedData = incomingMessage.split("#");
        strProcessingCode = strReceivedData[0];
        strAmount = strReceivedData[1];
        strTrack2Data = strReceivedData[2];
        strpin = strReceivedData[3];
        strPhoneNumber = strReceivedData[4];
        strBillNumber = strReceivedData[5];
        strRefNo = strReceivedData[6];
        strBiller = strReceivedData[7];
        strpaymentMode = strReceivedData[8];
        strDeviceid = strRefNo;

        //func.SendPOSResponse(strResponse, intid);
        if (strTrack2Data.contains("=")) {
            strCardInformation = strTrack2Data.split("=");
            strCardNumber = strCardInformation[0];
            int strlen = strCardNumber.length();
            if (strlen < 16) {
                strResponse = func.strPOSResponseHeader2(strDeviceid);
                strResponse += "--------------------------------" + "#";
                strResponse += "INVALID PAN #";
                strResponse += func.strPOSResponseFooter(strDeviceid);
                func.SendPOSResponse(strResponse, intid);
                return;
            }
            strExpiryDate = strCardInformation[1].substring(0, 4);
            //String[] strTrack2Data1 = strCardInformation[1].split("\\?");
            //strField35 = strCardInformation[0] + "=" + strTrack2Data1[0];

        } else if (strTrack2Data.contains("D")) {

            strCardInformation = strTrack2Data.split("D");
            strCardNumber = strCardInformation[0];
            int strlen = strCardNumber.length();
            if (strlen < 16) {
                strResponse = func.strPOSResponseHeader2(strDeviceid);
                strResponse += "--------------------------------" + "#";
                strResponse += "INVALID PAN #";
                strResponse += func.strPOSResponseFooter(strDeviceid);
                func.SendPOSResponse(strResponse, intid);
                return;
            }
            strExpiryDate = strCardInformation[1].substring(0, 4);
            //String[] strTrack2Data1 = strCardInformation[1].split("\\?");
            //strField35 = strCardInformation[0] + "=" + strTrack2Data1[0];
        }

        //send transactionDetails from pos to PaymentGateway
        //Auth key Variables
        String uniqueKey = "!Eclectic%IsThe BomB%Limited!??hehehe";
        String phoneNumber = strPhoneNumber;

        //Transaction Details Json Data
        JSONObject object = new JSONObject();
        object.put("Amount", strAmount);
        object.put("CardNo", strCardNumber);
        object.put("Channel", "POS");
        object.put("Organization", "Eclectics");
        object.put("ExpiryDate", strExpiryDate);
        object.put("RefNo", strRefNo);
        object.put("PhoneNumber", strPhoneNumber);
        object.put("MessageType", "0200");
        object.put("Country", "Kenya");
        object.put("Pin", strpin);
        object.put("ProcessingCode", strProcessingCode);
        object.put("Account", strBillNumber);
        object.put("Biller", strBiller);
        object.put("PaymentMode", strpaymentMode);

        //System.out.println("JSON DATA= "+object);
        String jsonString = object.toString().replaceAll("\"", "");

        String tobase64String = new BASE64Encoder().encode(jsonString.getBytes());//. Base64.getEncoder().encodeToString(jsonString.getBytes());
        //System.out.println("TO BASE64 STRING= "+tobase64String);

        //Auth key
        String authKeyString = uniqueKey + phoneNumber;
        //base64 of authKey
        String base64AuthString = new BASE64Encoder().encode(authKeyString.getBytes());// ++Base64.getEncoder().encodeToString(authKeyString.getBytes());
        //generate authKey sha512
        String sha512AuthKey = null;
        try {

            MessageDigest md = MessageDigest.getInstance("SHA-512");
            byte[] hash = md.digest(base64AuthString.getBytes());
            sha512AuthKey = convertToHex(hash);
        } catch (NoSuchAlgorithmException ex) {
            func.log("\nSEVERE GatewayBillsPayment() :: " + ex.getMessage() + "\n" + func.StackTraceWriter(ex),
                    "ERROR");
        }
        //System.out.println("SHA512 AUTH KEY= "+sha512AuthKey);
        //send request
        String response = authentication(tobase64String, sha512AuthKey);
        //System.out.println(response);

        String noCurly = response.replaceAll("[{}]", "");

        //            String status=null;
        //            
        //            Pattern pattern = Pattern.compile("{(.*?}'");
        //            Matcher matcher = pattern.matcher(mydata);
        //            if (matcher.find())
        //            {
        //                System.out.println(matcher.group(0));
        //            }
        String formatResponse[] = noCurly.split(",");

        strResponse = func.strPOSResponseHeader2(strDeviceid);
        strResponse += "--------------------------------" + "#";
        strResponse += "  BILLS PAYMENT  #";
        for (int i = 0; i < formatResponse.length; i++) {
            String[] myResponseParts = formatResponse[i].split("=");
            if (myResponseParts[1].contains("status")) {
                strResponse += formatResponse[i] + "#";
            }
        }

        strResponse += func.strPOSResponseFooter(strDeviceid);
        func.SendPOSResponse(strResponse, strDeviceid);

    } catch (Exception ex) {
        func.log("\nSEVERE GatewayBillsPayment() :: " + ex.getMessage() + "\n" + func.StackTraceWriter(ex),
                "ERROR");
    }
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 *///w w w.ja v  a2 s.co  m
public synchronized boolean createKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#createKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    boolean isComplete = false;
    OutputStream publicStream = null;
    OutputStream privateStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            if (!(keyDirectory.mkdirs())) {
                throw new KeyManagementException(
                        "Configured key directory does not exist and unable to create it");
            }
        }

        keyDirectory.setExecutable(true, true);

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm());
        keyGenerator.initialize(keyConfig.getKeySize(), random);
        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (keyPair != null) {
            File privateFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);
            File publicFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (!(privateFile.createNewFile())) {
                throw new IOException("Failed to store private key file");
            }

            if (!(publicFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            privateFile.setWritable(true, true);
            publicFile.setWritable(true, true);

            privateStream = new FileOutputStream(privateFile);
            publicStream = new FileOutputStream(publicFile);

            IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream);
            IOUtils.write(keyPair.getPublic().getEncoded(), publicStream);

            // assume success, as we'll get an IOException if the write failed
            isComplete = true;
        } else {
            throw new KeyManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (publicStream != null) {
            IOUtils.closeQuietly(publicStream);
        }

        if (privateStream != null) {
            IOUtils.closeQuietly(privateStream);
        }
    }

    return isComplete;
}

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

/**
 * This function creates the private key from the MD5Salt, the device and the private password
 *
 * @author Markus Eckhardt/*from   www . j a v  a  2 s . c  om*/
 *
 * @since 1.9.0
 */
@SuppressWarnings("null")
private void RecreateKeys() {
    if (StringUtils.isNotBlank(gatewayPassword) && StringUtils.isNotBlank(privatePassword) && MD5Salt != null) {
        byte[] MD5_K1 = null;
        byte[] MD5_K2_Init = null;
        byte[] MD5_K2_Private = null;
        byte[] bytesOfGatewayPassword = null;
        byte[] bytesOfPrivatePassword = null;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("No such algorithm, MD5: {}", e.getMessage());
        }

        /* First half of the key: MD5 of (GatewayPassword . Salt) */
        try {
            bytesOfGatewayPassword = gatewayPassword.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("No such encoding, UTF-8: {}", e.getMessage());
        }
        byte[] CombParts1 = new byte[bytesOfGatewayPassword.length + MD5Salt.length];
        System.arraycopy(bytesOfGatewayPassword, 0, CombParts1, 0, bytesOfGatewayPassword.length);
        System.arraycopy(MD5Salt, 0, CombParts1, bytesOfGatewayPassword.length, MD5Salt.length);
        MD5_K1 = md.digest(CombParts1);

        /* Second half of the key: - Initial: MD5 of ( Salt) */
        MD5_K2_Init = md.digest(MD5Salt);

        /* Second half of the key: - private: MD5 of ( Salt . PrivatePassword) */
        try {
            bytesOfPrivatePassword = privatePassword.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("No such encoding, UTF-8: {}", e.getMessage());
        }
        byte[] CombParts2 = new byte[bytesOfPrivatePassword.length + MD5Salt.length];
        System.arraycopy(MD5Salt, 0, CombParts2, 0, MD5Salt.length);
        System.arraycopy(bytesOfPrivatePassword, 0, CombParts2, MD5Salt.length, bytesOfPrivatePassword.length);
        MD5_K2_Private = md.digest(CombParts2);

        /* Create Keys */
        cryptKeyInit = new byte[MD5_K1.length + MD5_K2_Init.length];
        System.arraycopy(MD5_K1, 0, cryptKeyInit, 0, MD5_K1.length);
        System.arraycopy(MD5_K2_Init, 0, cryptKeyInit, MD5_K1.length, MD5_K2_Init.length);

        cryptKeyPriv = new byte[MD5_K1.length + MD5_K2_Private.length];
        System.arraycopy(MD5_K1, 0, cryptKeyPriv, 0, MD5_K1.length);
        System.arraycopy(MD5_K2_Private, 0, cryptKeyPriv, MD5_K1.length, MD5_K2_Private.length);

    }
}

From source file:org.whitesource.agent.hash.HashCalculator.java

public String calculateHash(File resourceFile, HashAlgorithm algorithm) throws IOException {
    MessageDigest messageDigest;// w  w w  .j a v  a2 s .com
    try {
        messageDigest = MessageDigest.getInstance(algorithm.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

    try (InputStream inputStream = new FileInputStream(resourceFile);
            BOMInputStream fis = new BOMInputStream(inputStream)) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int len = fis.read(buffer, 0, BUFFER_SIZE);
        while (len >= 0) {
            messageDigest.update(buffer, 0, len);
            len = fis.read(buffer, 0, BUFFER_SIZE);
        }
    }
    return toHex(messageDigest.digest());
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private KeyPairGenerator createKeyGenerator() throws CertificateException {
    try {//w  w  w  .  j av a 2  s  . c  o m
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        return kpg;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Failed to create RSA key pair generator." + e.getMessage());
    }
}