Example usage for java.security NoSuchAlgorithmException toString

List of usage examples for java.security NoSuchAlgorithmException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.intelligentz.appointmentz.controllers.register.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    MessageDigest messageDigest = null;
    try {//  w w w. j av  a 2  s.c o  m
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(register.class.getName()).log(Level.SEVERE, "Error:{0}", ex.toString());
    }
    messageDigest.reset();
    messageDigest.update(req.getParameter("form-password").getBytes(Charset.forName("UTF8")));
    final byte[] resultByte = messageDigest.digest();
    final String password = new String(Hex.encodeHex(resultByte));

    String userName = req.getParameter("form-hospital-id");
    String id = req.getParameter("form-id");
    //String password = req.getParameter("form-password");
    String hospitalName = req.getParameter("form-hospital-name");
    register(id, userName, password, hospitalName, req, res);

}

From source file:com.intelligentz.appointmentz.controllers.authenticate.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    MessageDigest messageDigest = null;
    try {/*from   w  ww.  jav  a2 s.  c om*/
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, "Error:{0}", ex.toString());
    }
    messageDigest.reset();
    messageDigest.update(req.getParameter("form-password").getBytes(Charset.forName("UTF8")));
    final byte[] resultByte = messageDigest.digest();
    final String password = new String(Hex.encodeHex(resultByte));

    String userName = req.getParameter("form-username");
    //String password = req.getParameter("form-password");
    authenticate(userName, password, req, res);

}

From source file:org.opendatakit.briefcase.util.EncryptionInformation.java

public EncryptionInformation(String base64EncryptedSymmetricKey, String instanceId, PrivateKey rsaPrivateKey)
        throws CryptoException {

    try {//from   w w  w .  j ava2  s.  co m
        // construct the base64-encoded RSA-encrypted symmetric key
        Cipher pkCipher;
        pkCipher = Cipher.getInstance(FileSystemUtils.ASYMMETRIC_ALGORITHM);
        // write AES key
        pkCipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
        byte[] encryptedSymmetricKey = Base64.decodeBase64(base64EncryptedSymmetricKey);
        byte[] decryptedKey = pkCipher.doFinal(encryptedSymmetricKey);
        cipherFactory = new CipherFactory(instanceId, decryptedKey);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting base64EncryptedKey Cause: " + e.toString());
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting base64EncryptedKey Cause: " + e.toString());
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting base64EncryptedKey Cause: " + e.toString());
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting base64EncryptedKey Cause: " + e.toString());
    } catch (BadPaddingException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting base64EncryptedKey Cause: " + e.toString());
    }
}

From source file:org.zuinnote.hadoop.bitcoin.format.BitcoinTransactionRecordReader.java

/**
*
* Read a next block. /*from   w w  w  . j  av a  2 s.co  m*/
*
* @param key is a 68 byte array (hashMerkleRoot, prevHashBlock, transActionCounter)
* @param value is a deserialized Java object of class BitcoinBlock
*
* @return true if next block is available, false if not
*/
public boolean next(BytesWritable key, BitcoinTransaction value) throws IOException {
    // read all the blocks, if necessary a block overlapping a split
    while (getFilePosition() <= getEnd()) { // did we already went beyond the split (remote) or do we have no further data left?
        if ((currentBitcoinBlock == null)
                || (currentBitcoinBlock.getTransactions().size() == currentTransactionCounterInBlock)) {
            try {
                currentBitcoinBlock = getBbr().readBlock();
                currentTransactionCounterInBlock = 0;
            } catch (BitcoinBlockReadException e) {
                // log
                LOG.error(e);
            }
        }

        if (currentBitcoinBlock == null)
            return false;
        BitcoinTransaction currentTransaction = currentBitcoinBlock.getTransactions()
                .get(currentTransactionCounterInBlock);
        // the unique identifier that is linked in other transaction is usually its hash
        byte[] newKey = new byte[0];
        try {
            newKey = BitcoinUtil.getTransactionHash(currentTransaction);
        } catch (NoSuchAlgorithmException nsae) {
            LOG.error("Cannot calculate transaction hash. Algorithm not available. Exception: "
                    + nsae.toString());
        }
        key.set(newKey, 0, newKey.length);
        value.set(currentTransaction);
        currentTransactionCounterInBlock++;
        return true;
    }
    return false;
}

From source file:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java

public JSONObject makeRequest(String method, Map<String, String> arguments)
        throws UnsupportedEncodingException {
    if (method == null) {
        return null;
    }//from  w  w  w . j a  v  a  2  s . c o  m
    if (arguments == null) {
        arguments = new HashMap<>();
    }
    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Key", key);
        String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8")));
        urlConnection.setRequestProperty("Sign", sign);
        urlConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new JSONObject(out.toString());
}

From source file:com.hkm.Application.appWork.java

private void showpackagesigning() {
    PackageInfo packageInfo;//from ww w . j  a v  a2s.  co  m
    try {
        packageInfo = getPackageManager().getPackageInfo("com.hkm.oc.app", PackageManager.GET_SIGNATURES);
        for (Signature signature : packageInfo.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String key = new String(Base64.encode(md.digest(), 0));
            // String key = new String(Base64.encodeBytes(md.digest()));
            Log.e("Hash key", sha1Hash(key));
        }
    } catch (PackageManager.NameNotFoundException e1) {
        Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
        Log.e("Exception", e.toString());
    }
}

From source file:umu.eadmin.servicios.umu2stork.UtilesRsa.java

public PrivateKey readPrivateKey(String filename) throws IOException {
    try {//from  w ww.  ja  v a  2 s. c  o  m
        logger.info("Start decoding RSA key in PEM format: " + filename);
        File keyFile = new File(filename);

        BufferedReader br = new BufferedReader(new FileReader(keyFile));
        StringBuffer keyBase64 = new StringBuffer();
        String line = br.readLine();
        while (line != null) {
            if (!(line.startsWith("-----BEGIN")) && !(line.startsWith("-----END"))) {
                keyBase64.append(line);
            }
            line = br.readLine();
        }
        br.close();
        logger.info("Decode RSA Key");
        byte[] fileBytes = new BASE64Decoder().decodeBuffer(keyBase64.toString());

        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(fileBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        logger.info("RSA Decode End: " + filename);
        pk = kf.generatePrivate(ks);
        return (pk);
    } catch (InvalidKeySpecException ex1) {
        throw new IOException("Invalid Key Spec: " + ex1.toString());
    } catch (NoSuchAlgorithmException ex2) {
        throw new IOException("No Such Algorithm: " + ex2.toString());
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API/*from  w w w.  j ava  2 s.  co m*/
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:io.github.retz.web.Client.java

protected Client(URI uri, Authenticator authenticator, boolean checkCert) {
    this.uri = Objects.requireNonNull(uri);
    this.authenticator = Objects.requireNonNull(authenticator);
    this.checkCert = checkCert;
    if (uri.getScheme().equals("https") && !checkCert) {
        LOG.warn(// w w w.jav a2  s  . c o  m
                "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message.");
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new WrongTrustManager() }, new java.security.SecureRandom());
            socketFactory = sc.getSocketFactory();
            hostnameVerifier = new NoOpHostnameVerifier();
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e.toString());
        } catch (KeyManagementException e) {
            throw new AssertionError(e.toString());
        }
    } else {
        socketFactory = null;
        hostnameVerifier = null;
    }
    this.retz = Retz.connect(uri, authenticator, socketFactory, hostnameVerifier);
    System.setProperty("http.agent", Client.VERSION_STRING);
}

From source file:org.zuinnote.hadoop.bitcoin.hive.udf.BitcoinTransactionHashUDF.java

/**
* This method evaluates a given Object (of type BitcoinTransaction) or a struct which has all necessary fields corresponding to a BitcoinTransaction. The first case occurs, if the UDF evaluates data represented in a table provided by the HiveSerde as part of the hadoocryptoledger library. The second case occurs, if BitcoinTransaction data has been imported in a table in another format, such as ORC or Parquet.
* 
* @param arguments array of length 1 containing one object of type BitcoinTransaction or a Struct representing a BitcoinTransaction
*
* @return BytesWritable containing a byte array with the double hash of the BitcoinTransaction
*
* @throws org.apache.hadoop.hive.ql.metadata.HiveException in case an itnernal HiveError occurred
*//*from   www  .j  a  v a 2  s .c o m*/

@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
    if (arguments == null)
        return null;
    if (arguments.length != 1)
        return null;
    BitcoinTransaction bitcoinTransaction = null;
    if (arguments[0].get() instanceof BitcoinTransaction) { // this happens if the table is in the original file format
        bitcoinTransaction = (BitcoinTransaction) arguments[0].get();
    } else { // this happens if the table has been imported into a more optimized analytics format, such as ORC. However, usually we expect that the first case will be used mostly (the hash is generated during extraction from the input format)
        // check if all bitcointransaction fields are available <struct<version:int,incounter:binary,outcounter:binary,listofinputs:array<struct<prevtransactionhash:binary,previoustxoutindex:bigint,txinscriptlength:binary,txinscript:binary,seqno:bigint>>,listofoutputs:array<struct<value:bigint,txoutscriptlength:binary,txoutscript:binary>>,locktime:int>
        Object originalObject = arguments[0].get();
        StructField versionSF = soi.getStructFieldRef("version");
        StructField incounterSF = soi.getStructFieldRef("incounter");
        StructField outcounterSF = soi.getStructFieldRef("outcounter");
        StructField listofinputsSF = soi.getStructFieldRef("listofinputs");
        StructField listofoutputsSF = soi.getStructFieldRef("listofoutputs");
        StructField locktimeSF = soi.getStructFieldRef("locktime");
        if ((versionSF == null) || (incounterSF == null) || (outcounterSF == null) || (listofinputsSF == null)
                || (listofoutputsSF == null) || (locktimeSF == null)) {
            LOG.info("Structure does not correspond to BitcoinTransaction");
            return null;
        }
        int version = wioi.get(soi.getStructFieldData(originalObject, versionSF));
        byte[] inCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject, incounterSF));
        byte[] outCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject, outcounterSF));
        int locktime = wioi.get(soi.getStructFieldData(originalObject, locktimeSF));
        Object listofinputsObject = soi.getStructFieldData(originalObject, listofinputsSF);
        ListObjectInspector loiInputs = (ListObjectInspector) listofinputsSF.getFieldObjectInspector();
        int loiInputsLength = loiInputs.getListLength(listofinputsObject);
        StructObjectInspector listofinputsElementObjectInspector = (StructObjectInspector) loiInputs
                .getListElementObjectInspector();
        List<BitcoinTransactionInput> listOfInputsArray = new ArrayList<BitcoinTransactionInput>(
                loiInputsLength);
        for (int i = 0; i < loiInputsLength; i++) {
            Object currentlistofinputsObject = loiInputs.getListElement(listofinputsObject, i);
            StructField prevtransactionhashSF = listofinputsElementObjectInspector
                    .getStructFieldRef("prevtransactionhash");
            StructField previoustxoutindexSF = listofinputsElementObjectInspector
                    .getStructFieldRef("previoustxoutindex");
            StructField txinscriptlengthSF = listofinputsElementObjectInspector
                    .getStructFieldRef("txinscriptlength");
            StructField txinscriptSF = listofinputsElementObjectInspector.getStructFieldRef("txinscript");
            StructField seqnoSF = listofinputsElementObjectInspector.getStructFieldRef("seqno");
            if ((prevtransactionhashSF == null) || (previoustxoutindexSF == null)
                    || (txinscriptlengthSF == null) || (txinscriptSF == null) || (seqnoSF == null)) {
                LOG.info("Invalid BitcoinTransactionInput detected at position " + i);
                return null;
            }
            byte[] currentPrevTransactionHash = wboi.getPrimitiveJavaObject(listofinputsElementObjectInspector
                    .getStructFieldData(currentlistofinputsObject, prevtransactionhashSF));
            long currentPreviousTxOutIndex = wloi.get(listofinputsElementObjectInspector
                    .getStructFieldData(currentlistofinputsObject, previoustxoutindexSF));
            byte[] currentTxInScriptLength = wboi.getPrimitiveJavaObject(listofinputsElementObjectInspector
                    .getStructFieldData(currentlistofinputsObject, txinscriptlengthSF));
            byte[] currentTxInScript = wboi.getPrimitiveJavaObject(listofinputsElementObjectInspector
                    .getStructFieldData(currentlistofinputsObject, txinscriptSF));
            long currentSeqNo = wloi.get(
                    listofinputsElementObjectInspector.getStructFieldData(currentlistofinputsObject, seqnoSF));
            BitcoinTransactionInput currentBitcoinTransactionInput = new BitcoinTransactionInput(
                    currentPrevTransactionHash, currentPreviousTxOutIndex, currentTxInScriptLength,
                    currentTxInScript, currentSeqNo);
            listOfInputsArray.add(currentBitcoinTransactionInput);

        }
        Object listofoutputsObject = soi.getStructFieldData(originalObject, listofoutputsSF);
        ListObjectInspector loiOutputs = (ListObjectInspector) listofoutputsSF.getFieldObjectInspector();
        StructObjectInspector listofoutputsElementObjectInspector = (StructObjectInspector) loiOutputs
                .getListElementObjectInspector();
        int loiOutputsLength = loiInputs.getListLength(listofinputsObject);
        List<BitcoinTransactionOutput> listOfOutputsArray = new ArrayList<BitcoinTransactionOutput>(
                loiOutputsLength);
        for (int i = 0; i < loiOutputsLength; i++) {
            Object currentlistofoutputsObject = loiOutputs.getListElement(listofoutputsObject, i);
            StructField valueSF = listofoutputsElementObjectInspector.getStructFieldRef("value");
            StructField txoutscriptlengthSF = listofoutputsElementObjectInspector
                    .getStructFieldRef("txoutscriptlength");
            StructField txoutscriptSF = listofoutputsElementObjectInspector.getStructFieldRef("txoutscript");
            if ((valueSF == null) || (txoutscriptlengthSF == null) || (txoutscriptSF == null)) {
                LOG.info("Invalid BitcoinTransactionOutput detected at position " + i);
                return null;
            }
            long currentValue = wloi.get(listofoutputsElementObjectInspector
                    .getStructFieldData(currentlistofoutputsObject, valueSF));
            byte[] currentTxOutScriptLength = wboi.getPrimitiveJavaObject(listofoutputsElementObjectInspector
                    .getStructFieldData(currentlistofoutputsObject, txoutscriptlengthSF));
            byte[] currentTxOutScript = wboi.getPrimitiveJavaObject(listofoutputsElementObjectInspector
                    .getStructFieldData(currentlistofoutputsObject, txoutscriptSF));
            BitcoinTransactionOutput currentBitcoinTransactionOutput = new BitcoinTransactionOutput(
                    currentValue, currentTxOutScriptLength, currentTxOutScript);
            listOfOutputsArray.add(currentBitcoinTransactionOutput);
        }
        bitcoinTransaction = new BitcoinTransaction(version, inCounter, listOfInputsArray, outCounter,
                listOfOutputsArray, locktime);

    }
    byte[] transactionHash = null;
    try {
        transactionHash = BitcoinUtil.getTransactionHash(bitcoinTransaction);
    } catch (NoSuchAlgorithmException nsae) {
        throw new HiveException(nsae.toString());
    } catch (IOException ioe) {
        throw new HiveException(ioe.toString());
    }
    return new BytesWritable(transactionHash);
}