Pages

Wednesday, April 8, 2020

File Encryption


File Encryption

Using the PGP we will encrypt the file from PDF. Once the file is downloaded by the bank they will decrypt using the private key.
Currently we are using the concurrent program “EXPD Common PGP Encryption Program” which will encrypt the files into pgp format.
Below is the pl/sql code developed in java, which is used to encrypt the file without running concurrent program.

Plsql Package:

CREATE OR REPLACE PACKAGE APPS.xxexpd_encrypt_pkg
IS 
      FUNCTION encrypt_file (p_interface_code IN VARCHAR2, p_file_absolute_path IN VARCHAR2)
        RETURN VARCHAR2;
END xxexpd_encrypt_pkg;
/      
CREATE OR REPLACE PACKAGE BODY APPS.xxexpd_encrypt_pkg
IS 
      FUNCTION encrypt_file (p_interface_code IN VARCHAR2, p_file_absolute_path IN VARCHAR2)
        RETURN VARCHAR2
    AS
        LANGUAGE JAVA
        NAME 'ExpdFileUtils.encryptFile(java.lang.String, java.lang.String) return java.lang.String' ;

END xxexpd_encrypt_pkg;
/

Java Code:

DROP JAVA SOURCE APPS."ExpdFileUtils";

CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED APPS."ExpdFileUtils"
as 
import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ExpdFileUtils {
    public static final String SUCCESS = "SUCCESS";
    public static final String MISSING_FILE_PATH = "File/Path does not exists";
    public static final String INVALID_FILE = "Invalid File.";
    public static final String INVALID_DIR = "Invalid Directory.";

    /**
     * Check if a given File or Path does exists
     *
     * @param absPath Absolute path of the Directory
     */
    public static String fileExists(String absPath) {
        File file = new File(absPath);
        if (file.exists()) {
            return SUCCESS;
        }
        return MISSING_FILE_PATH;
    }

    /**
     * Return the size of a file
     *
     * @param absFilePath Absolute path of the File
     */
    public static long getFileSize(String absFilePath) {
        File file = new File(absFilePath);
        if (!file.exists()) return -1;

        return file.length();
    }

    /**
     * Set read permission on the file to file/Directory
     *
     * @param absFilePath Absolute path of the file/Directory
     */
    public static void setReadPermission(String absFilePath) {
        File file = new File(absFilePath);
        if (file.exists()) {
            file.setReadable(true, false);
        }
    }

    /**
     * Set write permission on the file to file/Directory
     *
     * @param absFilePath Absolute path of the file/Directory
     */
    public static void setWritePermission(String absFilePath) {
        File file = new File(absFilePath);
        if (file.exists()) {
            file.setWritable(true, false);
        }
    }

    /**
     * Set execute permission on the file/Directory
     *
     * @param absFilePath Absolute path of the file/Directory
     */
    public static void setExecutePermission(String absFilePath) {
        File file = new File(absFilePath);
        if (file.exists()) {
            file.setExecutable(true, true);
        }
    }

    /**
     * Set All permission on the given File/Path
     *
     * @param absFilePath Full path of the file/Directory
     */
    public static String setAllPermission(String absFilePath) {
        File file = new File(absFilePath);
        // Check if file exists
        if (file.exists()) {
            file.setReadable(Boolean.TRUE, Boolean.TRUE); // Set Read permission for All
            // If file do not have write permission
            if (!file.canWrite() && !file.canExecute()) {
                try {
                    file.setExecutable(Boolean.TRUE, Boolean.TRUE); //Set Executable permission for All
                    // Set Write permission for All
                    if (!file.setWritable(Boolean.TRUE, Boolean.TRUE)) {
                        return "Unable to set Write permission on the File : " + absFilePath;
                    }
                } catch (Exception e) {
                    return e.getMessage();
                }
            }
        } else {
            return MISSING_FILE_PATH;
        }
        return SUCCESS;
    }

    /**
     * Method to delete a file/Directory
     *
     * @param absFilePath Full path of the file/Directory
     */
    public static String deleteFile(String absFilePath) {
        File file = new File(absFilePath);
        if (file.exists()) {
            if (!file.delete()) {
                return "Failed to delete the File/Path";
            }
        } else {
            return MISSING_FILE_PATH;
        }
        return SUCCESS;
    }

    /**
     * Method to move a file to another location
     *
     * @param absFilePath Full path of the file/Directory
     * @param newPath     new Path where original file is to be moved
     */
    public static String moveFile(String absFilePath, String newPath) {
        File origFile = new File(absFilePath);
        if (!origFile.exists()) return absFilePath.concat(" : ").concat(MISSING_FILE_PATH);
        if (!origFile.isFile()) return absFilePath.concat(" : ").concat(INVALID_FILE);

        File path = new File(newPath);
        if (!path.exists()) return newPath.concat(":").concat(MISSING_FILE_PATH);
        if (!path.isDirectory()) return newPath.concat(":").concat(INVALID_DIR);

        if (!origFile.renameTo(new File(newPath.concat(File.separator).concat(origFile.getName())))) {
            return "Failed to move the file";
        }
        return SUCCESS;
    }

    /**
     * Method to move a Directory to another location
     *
     * @param absDirPath Full path of the file/Directory
     * @param newPath    new Path where original file is to be moved
     */
    public static String moveDirectory(String absDirPath, String newPath) {
        File origFile = new File(absDirPath);
        if (!origFile.exists()) return absDirPath.concat(" : ").concat(MISSING_FILE_PATH);
        if (!origFile.isDirectory()) return absDirPath.concat(" : ").concat(INVALID_DIR);

        File path = new File(newPath);
        if (!path.exists()) return newPath.concat(":").concat(MISSING_FILE_PATH);
        if (!path.isDirectory()) return newPath.concat(":").concat(INVALID_DIR);

        if (!origFile.renameTo(new File(newPath.concat(File.separator).concat(origFile.getName())))) {
            return "Failed to move the Directory";
        }
        return SUCCESS;
    }

    /**
     * Create a Zip file for the given file
     *
     * @param absFilePath Full path of the file/Directory
     */
    public static String zipFile(String absFilePath) {
        File inputFile = new File(absFilePath);

        if (!inputFile.exists()) return MISSING_FILE_PATH;
        if (!inputFile.isFile()) return INVALID_FILE;

        String zipFileName = inputFile.getAbsolutePath().concat(".zip");
        try {
            System.out.println("zipFileName = " + zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));
            try {
                zos.putNextEntry(new ZipEntry(inputFile.getName()));
                FileInputStream fis = new FileInputStream(inputFile);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) > 0) {
                    zos.write(bytes, 0, length);
                }
                zos.closeEntry();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            zos.close();
        } catch (FileNotFoundException ex) {
            return (String.format("File %s does not exists : ", inputFile.getAbsolutePath()));
        } catch (IOException ex) {
            return (String.format("IO Exception %s", ex.getMessage()));
        }
        return SUCCESS;
    }

    /**
     * Create a zip file for the given file and move to an archive location
     *
     * @param absFilePath Full path of the file
     * @param newPath     Absolute path where file is to be archived
     */
    public static String archiveFile(String absFilePath, String newPath) {
        File origFile = new File(absFilePath);
        if (!origFile.exists()) return absFilePath.concat(" : ").concat(MISSING_FILE_PATH);
        if (!origFile.isFile()) return absFilePath.concat(" : ").concat(INVALID_FILE);

        File path = new File(newPath);
        if (!path.exists()) return newPath.concat(":").concat(MISSING_FILE_PATH);
        if (!path.isDirectory()) return newPath.concat(":").concat(INVALID_DIR);

        try {
            String status = zipFile(absFilePath);
            if (SUCCESS.equals(status)) {
                File zipFile = new File(absFilePath.concat(".zip"));
                if (zipFile != null && zipFile.length() > 0) {
                    // Move zip file to new location
                    zipFile.renameTo(new File(newPath.concat(File.separator).concat(zipFile.getName())));
                    // delete the original file
                    origFile.delete();
                }
            } else {
                return status;
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return SUCCESS;
    }

    /**
     * Get the list of files present in the Given directory path
     *
     * @param absDirPath Absolute Directory path
     * @return String having files separated by Separator Character
     */
    public static String listDirFiles(String absDirPath) {
        String sep = "|";
        File directory = new File(absDirPath);
        if (!directory.exists()) return MISSING_FILE_PATH;
        if (directory.isDirectory()) return INVALID_DIR;

        File[] filesInDir = directory.listFiles();
        StringBuilder result = null;

        if (filesInDir == null) {
            result = new StringBuilder("");
        } else {
            for (File file : directory.listFiles()) {
                if (file.isFile() && !file.isHidden()) {
                    if (result == null) {
                        result = new StringBuilder(file.getName());
                    } else {
                        result = result.append(sep).append(file.getName());
                    }
                }
            }
        }

        return result.toString();
    }

    /**
     * Get the output of given Input Stream
     *
     * @param in Input Stream to be read
     * @return String builder
     * @throws IOException
     */
    private static StringBuilder getCommandOutput(InputStream in) throws IOException {
        StringBuilder output = new StringBuilder();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = stdInput.readLine()) != null) {
            output.append(line).append(System.getProperty("line.separator"));
        }
        return output;
    }


    /**
     * Encrypt the given File
     *
     * @return
     */
    public static String encryptFile(String interfaceCode, String absFilePath) {
        StringBuilder output = null;
        String signingKey = null, recipient = null;
        File inputFile = new File(absFilePath);

        // Check if file exists and valid
        if (!inputFile.exists()) return MISSING_FILE_PATH;
        if (!inputFile.isFile()) return INVALID_FILE;

        try {
            // Get the Required Details
            Connection conn = DriverManager.getConnection("jdbc:default:connection");
            String sql = "SELECT signing_key, recipient FROM xxexpd_common_pgp_t WHERE rice_id = :1 AND  method = 'ENCRYPTION'";
            OraclePreparedStatement stmt = (OraclePreparedStatement) conn.prepareStatement(sql);
            stmt.setString(1, interfaceCode);
            OracleResultSet rs = (OracleResultSet) stmt.executeQuery();
            if (rs != null && rs.next()) {
                signingKey = rs.getString(1);
                recipient = rs.getString(2);
                rs.close();
            }
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return e.getMessage();
        }

        if (signingKey == null || recipient == null) {
            return "Unable to retrieve information from table.";
        } else {
            try {
                String encryptedFilePath = absFilePath.concat(".pgp");
                // Execute the command
                String cmd = String.format("gpg --trust-model always -u %s -r %s --output %s ", signingKey, recipient, encryptedFilePath);
                if (interfaceCode.contains("E.259_NOR")) {
                    cmd = cmd + "--armor ";
                }
                cmd = cmd + String.format("--encrypt %s", absFilePath);

                Process process = Runtime.getRuntime().exec(cmd);
                process.waitFor();
                int exitVal = process.exitValue();
                return SUCCESS;

            } catch (IOException e) {
                e.printStackTrace();
                return e.getMessage();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }

};

/


Eg.
select xxexpd_file_utility_pkg.encrypt_file ('E.990','/u04/oracle/R12/ORADEV/XXEXPD/12.0.0/data/inbound/E.629/bad/Load_Data.csv') from dual;

A file with .pgp will gets created in the same file location once the file is encrypted.

No comments:

Post a Comment