Java tutorial
/* * 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 view; import Db.Dbcon; import General.Configuration; import General.Nimbus; import java.awt.Component; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.Writer; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Random; /** * * @author Jithinpv */ public class ChooseFile extends javax.swing.JFrame { public static String path; String selectedFilePath; String attr_1_file_name; String attr_2_file_size; String attr_3_file_extension; String attr_4_file_created_time; static double rangeMax = 999999999; static double rangeMin = 1111; static String secretKeyName = ""; static String masterKeyName = ""; static String privateKeyName = ""; /** * Creates new form ChooseFile */ public ChooseFile() { Nimbus.loadLoogAndFeel(); initComponents(); this.setLocationRelativeTo(null); Configuration.setIconOnLabel("chooseFile.jpg", bg); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); bg = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setText("Choose File :"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(45, 51, 112, -1)); jButton1.setText("Browse"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(175, 47, 112, -1)); jButton2.setText("ENCRYPT"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 136, -1, -1)); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(175, 88, 112, 22)); jLabel3.setText("File Encryption"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(114, 11, 131, -1)); jButton3.setText("BACK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(183, 136, -1, -1)); bg.setText("jLabel4"); getContentPane().add(bg, new org.netbeans.lib.awtextra.AbsoluteConstraints(-6, -6, 350, 230)); pack(); }// </editor-fold>//GEN-END:initComponents private void encryptFile(File file) { try { FileInputStream dataInFile = new FileInputStream(file); byte fileData[] = new byte[(int) file.length()]; dataInFile.read(fileData); dataInFile.close(); int G = (int) generateCyclicRandomNumber(); int G1 = (int) generateCyclicRandomNumber(); int e = getAttributeCoefficient(attr_1_file_name); int g = getAttributeCoefficient(attr_2_file_size); int u = getAttributeCoefficient(attr_3_file_extension); int v = getAttributeCoefficient(attr_4_file_created_time); System.out.println(e); System.out.println(g); System.out.println(u); System.out.println(v); String privateKeyPath = ""; String masterKeyPath = ""; String secretKeyPath = ""; int privateKey = generatePrivateKey(e, g, u, v); System.out.println("privateKey " + privateKey); int masterKey = generateMasterKey(); System.out.println("masterKey " + masterKey); int secretKey = generateSecretKey(masterKey, privateKey); String fileDataString = encodeData(fileData, masterKey, secretKey, privateKey); System.out.println(fileDataString); Writer out = new BufferedWriter(new FileWriter(file)); out.write(fileDataString); out.close(); } catch (Exception e) { e.printStackTrace(); } } private static int generateSecretKey(int a, int b) { int c = a - b; if (c < 0) { c = c * -1; } try { File secretKeyFile = new File(Configuration.allKeys + "secret_" + System.currentTimeMillis() + ".key"); secretKeyName = secretKeyFile.getName(); Writer out = new BufferedWriter(new FileWriter(secretKeyFile)); out.write(c + ""); out.close(); } catch (Exception e) { e.printStackTrace(); } return c; } private static int generateMasterKey() { int masterKey = 1; Random r = new Random(); masterKey = r.nextInt(); if (masterKey < 0) { masterKey = masterKey * -1; } try { File masterKeyFile = new File(Configuration.allKeys + "master_" + System.currentTimeMillis() + ".key"); masterKeyName = masterKeyFile.getName(); Writer out = new BufferedWriter(new FileWriter(masterKeyFile)); out.write(masterKey + ""); out.close(); } catch (Exception e) { e.printStackTrace(); } return masterKey; } private static int generatePrivateKey(int e, int g, int u, int v) { int privateKey = ((e + g) * u) / v; File privateKeyFile = new File(Configuration.allKeys + "private_" + System.currentTimeMillis() + ".key"); privateKeyName = privateKeyFile.getName(); try { Writer out = new BufferedWriter(new FileWriter(privateKeyFile)); out.write(privateKey + ""); out.close(); } catch (Exception ex) { ex.printStackTrace(); } return privateKey; } private static double generateCyclicRandomNumber() { Random r = new Random(); double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble(); return randomValue; } private static int getAttributeCoefficient(String attribute) { int attributeCoefficient = 0; for (int i = 0; i < attribute.length(); i++) { char character = attribute.charAt(0); int coefficient = (int) character; attributeCoefficient += coefficient; } return attributeCoefficient; } public static String encodeData(byte[] imagebytearray, int masterKey, int secretKey, int privateKey) { ENC.setMasterKey(masterKey); ENC.setSecretKey(secretKey); ENC.setPrivateKey(privateKey); return ENC.encode(imagebytearray); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String filename = jLabel2.getText(); if (filename.equals("")) { JOptionPane.showMessageDialog(rootPane, "Choose file"); } else { // selectedFilePath encryptFile(new File(Configuration.dataCloud + selectedFilePath)); Dbcon dbcon = new Dbcon(); int ins = dbcon.insert( "insert into tbl_file_encryption_logs(encrypted_file_path,data_member_id,attr_1 ,attr_2,attr_3,attr_4,created_at,master_key,secret_key,private_key)values('" + selectedFilePath + "','" + DataMemberLogin.logged_in_user_id + "','" + attr_1_file_name + "','" + attr_2_file_size + "','" + attr_3_file_extension + "','" + attr_4_file_created_time + "','" + System.currentTimeMillis() + "', '" + masterKeyName + "' , '" + secretKeyName + "' , '" + privateKeyName + "' )"); if (ins > 0) { this.dispose(); UploadFile uploadFile = new UploadFile(attr_1_file_name, attr_2_file_size, attr_3_file_extension, attr_4_file_created_time, privateKeyName, masterKeyName, secretKeyName); uploadFile.setVisible(true); } } }//GEN-LAST:event_jButton2ActionPerformed static class ENC { static int privateKey; static int secretKey; static int masterKey; public static void setMasterKey(int masterKey) { ENC.masterKey = masterKey; } public static void setSecretKey(int secretKey) { ENC.secretKey = secretKey; } public static void setPrivateKey(int privateKey) { ENC.privateKey = privateKey; } public static String encode(byte[] imagebytearray) { return Base64.encode(imagebytearray); } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: this.dispose(); DataMemberHome dataMemberHome = new DataMemberHome(); dataMemberHome.setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog((Component) evt.getSource()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { path = file.toString(); System.out.println(path); String name = chooser.getSelectedFile().getName(); jLabel2.setText(name); Path filePath = Paths.get(file.getPath()); BasicFileAttributes bfa = Files.readAttributes(filePath, BasicFileAttributes.class); attr_1_file_name = FilenameUtils.getBaseName(file.getName()); attr_2_file_size = (file.length()) + ""; attr_3_file_extension = FilenameUtils.getExtension(file.getPath()); attr_4_file_created_time = bfa.creationTime().toMillis() + ""; selectedFilePath = System.currentTimeMillis() + "." + FilenameUtils.getExtension(path); FileUtils.copyFile(file, new File(Configuration.dataCloud + selectedFilePath)); } catch (Exception ex) { System.out.println("problem accessing file" + file.getAbsolutePath()); } } else { System.out.println("File access cancelled by user."); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ChooseFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChooseFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChooseFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChooseFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ChooseFile().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bg; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }