smsapp.utils.Utils.java Source code

Java tutorial

Introduction

Here is the source code for smsapp.utils.Utils.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package smsapp.utils;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
//import gnu.io.*;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import smsapp.controllers.ControllerWhatsapp;

/**
 *
 * @author RESEARCH2
 */
public final class Utils {

    private static SecretKeySpec secretKey;
    private static byte[] key;
    private static String finalFile = "";
    private static final String workingDir = System.getProperty("user.dir");
    private String date = null;
    private String time = null;
    private TimeZone tz = null;
    private GregorianCalendar gCalendar = null;

    public Utils() {
        initializeSystemTime();
    }

    public static String correctFilePath(String foldername, String filename) {

        finalFile = workingDir + File.separator + foldername + File.separator + filename;
        return finalFile;

    }

    public static ArrayList<String> commPortsList() {
        Enumeration pList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> comPorts = new ArrayList<>();

        while (pList.hasMoreElements()) {
            CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();

            if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                comPorts.add(cpi.getName());
            }
        }
        return comPorts;
    }

    public static void setKey(String myKey) {

        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            System.out.println(key.length);
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16); // use only first 128 bit
            System.out.println(key.length);
            System.out.println(new String(key, "UTF-8"));
            secretKey = new SecretKeySpec(key, "AES");

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            ApplicationErrors.logErrors(Utils.class.getName(), e.getMessage());
        }

    }

    public static String encrypt(String strToEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) {
            ApplicationErrors.logErrors(Utils.class.getName(), e.getMessage());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            ApplicationErrors.logErrors(Utils.class.getName(), e.getMessage());
        }
        return null;
    }

    public void initializeSystemTime() {
        tz = TimeZone.getTimeZone("Africa/Nairobi");
        gCalendar = new GregorianCalendar();
        gCalendar.setTimeZone(tz);
    }

    public String getFullTime() {
        time = "" + gCalendar.get(Calendar.HOUR_OF_DAY) + ":" + gCalendar.get(Calendar.MINUTE) + ":"
                + gCalendar.get(Calendar.SECOND);
        return time;
    }

    public String getFullDate() {
        date = "" + gCalendar.get(Calendar.DATE) + "-" + (gCalendar.get(Calendar.MONTH) + 1) + "-"
                + gCalendar.get(Calendar.YEAR);
        return date;
    }

    public String getFullDateTime() {
        date = "" + gCalendar.get(Calendar.DATE) + "-" + (gCalendar.get(Calendar.MONTH) + 1) + "-"
                + gCalendar.get(Calendar.YEAR);
        time = "" + gCalendar.get(Calendar.HOUR_OF_DAY) + "." + gCalendar.get(Calendar.MINUTE) + "."
                + gCalendar.get(Calendar.SECOND);
        return date + "[" + time + "])";
    }

    public String getHumanDateTime() {
        date = "" + gCalendar.get(Calendar.DATE) + "-" + (gCalendar.get(Calendar.MONTH) + 1) + "-"
                + gCalendar.get(Calendar.YEAR);
        time = "" + gCalendar.get(Calendar.HOUR_OF_DAY) + ":" + gCalendar.get(Calendar.MINUTE) + ":"
                + gCalendar.get(Calendar.SECOND);
        return "Date: " + date + "  /  " + time;
    }

    public String getTabbedFullDateTime() {
        date = "" + gCalendar.get(Calendar.DATE) + "-" + (gCalendar.get(Calendar.MONTH) + 1) + "-"
                + gCalendar.get(Calendar.YEAR);
        time = "" + gCalendar.get(Calendar.HOUR_OF_DAY) + "." + gCalendar.get(Calendar.MINUTE) + "."
                + gCalendar.get(Calendar.SECOND);
        return date + "[" + time + "]";
    }

    public static String getSQLDate(int yr, int mnth, int day) {
        String sqldate = Integer.toString(day);
        String sqlmnth = Integer.toString(mnth);
        String sqlDate;
        if (day < 10) {
            sqldate = "0" + day;
        }
        if (mnth < 10) {
            sqlmnth = "0" + mnth;
        }
        sqlDate = yr + "-" + sqlmnth + "-" + sqldate;
        return sqlDate;
    }

    public static void openFile(String folderName, String fileName) {
        File f = new File(folderName + "" + File.separator + "" + fileName);
        Desktop dt = Desktop.getDesktop();
        try {
            dt.open(f);
        } catch (IOException ex) {
            Logger.getLogger(ControllerWhatsapp.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        System.out.println("Done.");
    }

    public static void browseFileLocation(String folderName) {
        File f = new File(folderName + "" + File.separator + "");
        Desktop dt = Desktop.getDesktop();
        try {
            dt.open(f);
        } catch (IOException ex) {
            Logger.getLogger(ControllerWhatsapp.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        System.out.println("Done.");
    }

    public static boolean deleteTempFile(String fileName) {
        try {

            File file = new File("_gendocs" + File.separator + fileName);
            return file.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
    }

    public static void main(String args[]) {
        setKey("simpleencrypt");
        System.out.println("encrypted " + encrypt("hello world"));
        System.out.println("decrypted " + decrypt(encrypt("hello world")));
    }

}