Example usage for java.security InvalidKeyException printStackTrace

List of usage examples for java.security InvalidKeyException printStackTrace

Introduction

In this page you can find the example usage for java.security InvalidKeyException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.filelocker.andy.MainActivity.java

public void lockButton_Click(View view) {

    TextView vPasswordText = (TextView) findViewById(R.id.passwordText);
    TextView vFileChooserText = (TextView) findViewById(R.id.fileChooserText);

    String myPassword = vPasswordText.getText().toString();

    vPasswordText.setText("");

    if (vFileChooserText.getText().toString().equals("") || myPassword.equals("")) {
        Toast toast;//from  w  ww.jav  a  2 s .  c  o m
        if (vFileChooserText.getText().toString().equals("")) {
            toast = Toast.makeText(getApplicationContext(), "File Not Choosen", Toast.LENGTH_LONG);
            toast.show();
        } else if (myPassword.equals("")) {
            toast = Toast.makeText(getApplicationContext(), "Password Field Empty", Toast.LENGTH_LONG);
            toast.show();
        }

        return;
    } else if (!(vFileChooserText.getText().toString()
            .substring(vFileChooserText.getText().toString().lastIndexOf('.') + 1).equals("encrypt"))) {

        AES_Encryption en = new AES_Encryption(myPassword);
        /*
         * setup encryption cipher using password. print out iv and salt
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.setupEncrypt();
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidParameterSpecException ex) {
            ex.printStackTrace();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        /*
         * write out encrypted file
         */
        try {

            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString() + ".encrypt");

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.WriteEncryptedFile(vInFile, vOutFile);

            Toast toast = Toast.makeText(getApplicationContext(), "Encryption Complete", Toast.LENGTH_LONG);
            toast.show();
            vInFile.delete();

        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else {

        /*
         * decrypt file
         */
        AES_Encryption dc = new AES_Encryption(myPassword);
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.setupDecrypt(vInFile);
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidAlgorithmParameterException ex) {
            ex.printStackTrace();
        } catch (DecoderException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {

            ex.printStackTrace();
        }

        /*
         * write out decrypted file
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString().substring(0,
                    vFileChooserText.getText().toString().length() - 8));

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.ReadEncryptedFile(vInFile, vOutFile);
            vInFile.delete();

            Toast toast = Toast.makeText(getApplicationContext(), "Decryption Complete", Toast.LENGTH_LONG);
            toast.show();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

From source file:edu.cwru.apo.API.java

public boolean callMethod(Methods method, AsyncRestRequestListener<Methods, JSONObject> callback,
        JSONObject json, String... params) {
    boolean result = false;
    switch (method) {
    case serviceReport:
        // set up a phone request
        ApiCall reportCall = new ApiCall(context, callback, method, "Submitting Service Report", "Please Wait");
        RestClient reportClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);

        // if both exist add parameters to call and execute
        String reportInstallID = Installation.id(context.getApplicationContext());
        String reportTimestamp = Long.toString(Auth.getTimestamp());

        JSONObject reportUserData = new JSONObject();

        try {//  w ww . j  a  v  a2s .  c  o  m
            reportUserData.put("date", params[0]);
            reportUserData.put("projectName", params[1]);
            reportUserData.put("projectLocation", params[2]);
            reportUserData.put("inOut", params[3]);
            reportUserData.put("offCampus", params[4]);
            reportUserData.put("serviceType", params[5]);
            reportUserData.put("travelTime", params[6]);
            reportUserData.put("comments", params[7]);
            reportUserData.put("numBros", params[8]);
            reportUserData.put("brothers", json);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String reportUD = URLEncoder.encode(reportUserData.toString());
        String reportData = "serviceReport" + reportTimestamp + reportInstallID + reportUserData.toString();
        reportClient.AddParam("method", "serviceReport");
        reportClient.AddParam("installID", reportInstallID);
        reportClient.AddParam("timestamp", reportTimestamp);
        reportClient.AddParam("userData", reportUD);
        try {
            reportClient.AddParam("HMAC", Auth.Hmac.generate(reportData).toString());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

        //execute the call
        reportCall.execute(reportClient);
        result = true;
        break;
    }
    return result;
}

From source file:com.scm.reader.livescanner.search.ImageRecognizer.java

public Search query(final Context context, Search dataToPopulate) throws IOException {

    String searchUrl = KConfig.getConfig().getServer();

    LogUtils.logDebug("qurl " + searchUrl);

    String apiKey = null;//from  ww w  .  ja v a  2  s.c  o  m
    String apiSecret = null;

    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        apiKey = bundle.getString(API_KEY_NAME);
        apiSecret = bundle.getString(API_SECRET_NAME);

    } catch (NameNotFoundException e) {
        Log.e(TAG, "Failed to load API_KEY or SECRET from meta-data, NameNotFound: " + e.getMessage());
        throw new RuntimeException("API_KEY or SECRET not found.");
    } catch (NullPointerException e) {
        Log.e(TAG, "Failed to load API_KEY or SECRET from meta-data, NullPointer: " + e.getMessage());
        throw new RuntimeException("API_KEY or SECRET not found.");
    }

    SearchRequestBuilder requestBuilderV4 = new SearchRequestBuilder(
            new SearchRequestData(dataToPopulate.getImage(), dataToPopulate.getLatitude(),
                    dataToPopulate.getLongitude(), searchUrl, getDeviceId(context)),
            getPackageInfo(context), apiKey, apiSecret);

    String response = "";

    try {

        Map<String, String> params = new HashMap<String, String>();
        params.put("location:", dataToPopulate.getLatitude() + ", " + dataToPopulate.getLongitude());
        response = requestBuilderV4.query();

    } catch (InvalidKeyException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        LogUtils.logWarn("IO exception while sending HTTP request and parsing response", e);
        throw e;
    }

    // Print the response to console
    System.out.println("HTTP Status: " + requestBuilderV4.getResponseStatus());
    System.out.println("HTTP Response: " + requestBuilderV4.getResponseBody());

    Search result = null;
    try {
        result = parseJSON(context, response, dataToPopulate);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;

}

From source file:edu.cwru.apo.API.java

public boolean callMethod(Methods method, AsyncRestRequestListener<Methods, JSONObject> callback,
        String... params) {//from w w w .j  a  v  a  2 s  .  c  om
    boolean result = false;
    switch (method) {
    case checkAppVersion:
        ApiCall checkVersionCall = new ApiCall(context, callback, method, "Checking for updates",
                "Please Wait");
        RestClient checkVersionClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);
        checkVersionClient.AddParam("method", "appVersion");

        //execute the call
        checkVersionCall.execute(checkVersionClient);
        result = true;
        break;
    case login:
        if (params.length != 2)
            break;
        if (params[0] == null || params[1] == null)
            break;

        // set up a login request NOTE: Must be HTTPS!!
        ApiCall loginCall = new ApiCall(context, callback, method, "Logging In", "Please Wait");
        RestClient loginClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);
        loginClient.AddParam("method", "login");
        loginClient.AddParam("user", params[0]);
        loginClient.AddParam("pass", Auth.md5(params[1]).toString());
        loginClient.AddParam("installID", URLEncoder.encode(Installation.id(context.getApplicationContext())));
        loginClient.AddParam("secretKey", Auth.Hmac.getSecretKey().toString());

        //execute the call
        loginCall.execute(loginClient);
        result = true;
        break;
    case checkCredentials:
        // set up a checkCredentials request
        ApiCall checkCredentialsCall = new ApiCall(context, callback, method);
        RestClient checkCredentialsClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);

        // if both exist add parameters to call and execute
        String installID = Installation.id(context.getApplicationContext());
        String timestamp = Long.toString(Auth.getTimestamp());
        String data = "checkCredentials" + timestamp + installID;
        checkCredentialsClient.AddParam("method", "checkCredentials");
        checkCredentialsClient.AddParam("installID", installID);
        checkCredentialsClient.AddParam("timestamp", timestamp);
        try {
            checkCredentialsClient.AddParam("HMAC", Auth.Hmac.generate(data).toString());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

        //execute the call
        checkCredentialsCall.execute(checkCredentialsClient);
        result = true;
        break;
    case logout:
        // set up a logout request
        break;
    case resetPassword:
        // set up a resetPassword request
        break;
    case getContract:
        // set up a getContract request
        ApiCall getContractCall = new ApiCall(context, callback, method, "Loading", "Please Wait");
        RestClient getContractClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);

        // if both exist add parameters to call and execute
        String contractinstallID = Installation.id(context.getApplicationContext());
        String contracttimestamp = Long.toString(Auth.getTimestamp());
        String contractdata = "getContract" + contracttimestamp + contractinstallID;
        getContractClient.AddParam("method", "getContract");
        getContractClient.AddParam("installID", contractinstallID);
        getContractClient.AddParam("timestamp", contracttimestamp);
        try {
            getContractClient.AddParam("HMAC", Auth.Hmac.generate(contractdata).toString());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

        //execute the call
        getContractCall.execute(getContractClient);
        result = true;
        break;

    case phone:
        // set up a phone request
        ApiCall phoneCall = new ApiCall(context, callback, method, "Updating User Directory", "Please Wait");
        RestClient phoneClient = new RestClient(secureUrl, httpClient, RequestMethod.POST);

        // if both exist add parameters to call and execute
        String phoneInstallID = Installation.id(context.getApplicationContext());
        String phoneTimestamp = Long.toString(Auth.getTimestamp());

        JSONObject phoneUserData = new JSONObject();
        try {
            if (params != null)
                phoneUserData.put("updateTime", Long.parseLong(params[0]));
            else
                phoneUserData.put("updateTime",
                        getUpdateTime(context.getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)));

            String phoneUD = URLEncoder.encode(phoneUserData.toString());
            String phoneData = "phone" + phoneTimestamp + phoneInstallID + phoneUserData.toString();
            phoneClient.AddParam("method", "phone");
            phoneClient.AddParam("installID", phoneInstallID);
            phoneClient.AddParam("timestamp", phoneTimestamp);
            phoneClient.AddParam("userData", phoneUD);

            phoneClient.AddParam("HMAC", Auth.Hmac.generate(phoneData).toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //execute the call
        phoneCall.execute(phoneClient);
        result = true;
        break;
    }
    return result;
}

From source file:de.fhg.fokus.hss.server.zh.HSSzhOperationsImpl.java

/**
 * It handles the synchronization of the SQN-MS with the SQN-HE
 * @throws DiameterException/*  ww  w  .  j  a  v a 2  s  .  co m*/
 * @return a list of authentication vectorList
 */
public ArrayList performSynchronization() throws DiameterException {
    LOGGER.info("Handling Synchronization between Mobile Station and Home Environment!");
    byte[] sipAuthorization = sipAuthDataItem.sipAuthorization;

    HexCoDec codec;
    codec = new HexCoDec();

    byte[] secretKey = codec.decode(impi.getSkey());
    byte[] amf = codec.decode(impi.getAmf());

    try {
        // get op and generate opC   
        byte[] op = codec.decode(impi.getOperatorId());
        byte[] opC = Milenage.generateOpC(secretKey, op);

        String authScheme = impi.getAuthScheme();
        Inet4Address ip = impi.getIP();

        // sqnHE - represent the SQN from the HSS
        // sqnMS - represent the SQN from the client side
        byte[] sqnHe = codec.decode(impi.getSqn());
        sqnHe = DigestAKA.getNextSQN(sqnHe, HSSProperties.IND_LEN);

        byte[] nonce = new byte[32];
        byte[] auts = new byte[14];
        int k = 0;
        for (int i = 0; i < 32; i++, k++) {
            nonce[k] = sipAuthorization[i];
        }
        k = 0;
        for (int i = 32; i < 46; i++, k++) {
            auts[k] = sipAuthorization[i];
        }

        byte[] rand = new byte[16];
        k = 0;
        for (int i = 0; i < 16; i++, k++) {
            rand[k] = nonce[i];
        }

        byte[] ak = null;
        if (HSSProperties.USE_AK) {
            ak = Milenage.f5star(secretKey, rand, opC);
        }

        byte[] sqnMs = new byte[6];
        k = 0;
        if (HSSProperties.USE_AK) {
            for (int i = 0; i < 6; i++, k++) {
                sqnMs[k] = (byte) (auts[i] ^ ak[i]);
            }
            LOGGER.warn("USE_AK is enabled and will be used in Milenage algorithm!");
        } else {
            for (int i = 0; i < 6; i++, k++) {
                sqnMs[k] = auts[i];
            }
            LOGGER.warn("USE_AK is NOT enabled and will NOT be used in Milenage algorithm!");
        }

        if (DigestAKA.SQNinRange(sqnMs, sqnHe, HSSProperties.IND_LEN, HSSProperties.delta, HSSProperties.L)) {
            LOGGER.info("The new generated SQN value shall be accepted on the client, abort synchronization!");
            k = 0;
            byte[] copySqnHe = new byte[6];
            for (int i = 0; i < 6; i++, k++) {
                copySqnHe[k] = sqnHe[i];
            }

            AuthenticationVector aVector = DigestAKA.getAuthenticationVector(authScheme, secretKey, opC, amf,
                    copySqnHe);
            ArrayList vectorsList = new ArrayList();
            vectorsList.add(aVector);

            // update Cxdata
            impi.setSqn(codec.encode(sqnHe));
            HibernateUtil.getCurrentSession().update(impi);
            return vectorsList;
        }

        byte xmac_s[] = Milenage.f1star(secretKey, rand, opC, sqnMs, amf);
        byte mac_s[] = new byte[8];
        k = 0;
        for (int i = 6; i < 14; i++, k++) {
            mac_s[k] = auts[i];
        }

        for (int i = 0; i < 8; i++)
            if (xmac_s[i] != mac_s[i]) {
                LOGGER.error("XMAC and MAC are different! User not authorized in performing synchronization!");
                throw new DiameterBaseException(5012);
            }

        sqnHe = sqnMs;
        sqnHe = DigestAKA.getNextSQN(sqnHe, HSSProperties.IND_LEN);
        LOGGER.info("Synchronization of SQN_HE with SQN_MS was completed successfully!");

        byte[] copySqnHe = new byte[6];
        k = 0;
        for (int i = 0; i < 6; i++, k++) {
            copySqnHe[k] = sqnHe[i];
        }
        AuthenticationVector aVector = DigestAKA.getAuthenticationVector(authScheme, secretKey, opC, amf,
                copySqnHe);
        ArrayList vectorsList = new ArrayList();
        vectorsList.add(aVector);

        // update Cxdata
        impi.setSqn(codec.encode(sqnHe));
        HibernateUtil.getCurrentSession().update(impi);
        return vectorsList;

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return new ArrayList();
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Encodes a request returning the encoded body
 *
 * @param body// www .j a va2 s  .c  om
 * @return the encoded body.
 * @throws IOException
 */
public String encodeMessage(String body) throws IOException {
    checkActive();
    if (encryptionEnabled) {
        try {
            JSONObject json = new JSONObject();
            json.put("payload", new JSONArray(encrypt(body)));
            return json.toString();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (BadPaddingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (JSONException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (InvalidKeySpecException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (InvalidParameterSpecException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        }

    }
    return body;
}

From source file:edu.rice.batchsig.bench.BenchSigner.java

SignaturePrimitives setupCipher(String signer_id) {
    try {//from   ww w  . ja  v a  2 s  .c om
        int bits;
        String type = "";
        if (commands.hasOption("sha1")) {
            type += "SHA1";
        } else if (commands.hasOption("sha256")) {
            type += "SHA256";
        } else {
            throw new Error();
        }

        type += "with";

        if (commands.hasOption("dsa")) {
            bits = Integer.parseInt(commands.getOptionValue("dsa", "1024"));
            type += "DSA";
        } else if (commands.hasOption("rsa")) {
            bits = Integer.parseInt(commands.getOptionValue("rsa", "2048"));
            type += "RSA";
        } else {
            throw new Error();
        }

        // Must set the prims first, used with the other.
        if (isTrace && isVerifying) {
            return MultiplexedPublicKeyPrims.make(type, bits, commands.getOptionValue("provider"));
        } else {
            return PublicKeyPrims.make(signer_id, type, bits, commands.getOptionValue("provider"));
        }
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    throw new Error("Failed");
}