Advertisement
Guest User

Decryption

a guest
Oct 21st, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.06 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. package Encrypt;
  8.  
  9.  
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import javax.swing.JFileChooser;
  13. import javax.swing.JOptionPane;
  14. import javax.swing.JPanel;
  15. import java.io.File;
  16. import java.io.FileInputStream;
  17. import java.io.FileNotFoundException;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.ObjectInputStream;
  21. import java.io.ObjectOutputStream;
  22. import java.security.KeyPair;
  23. import java.security.KeyPairGenerator;
  24. import java.security.PrivateKey;
  25. import java.security.PublicKey;
  26. import java.util.Arrays;
  27. import javax.crypto.Cipher;
  28. /**
  29.  *
  30.  * @author Proking
  31.  */
  32. public class DecryptForm extends javax.swing.JInternalFrame {
  33.     String filename = "";
  34.     String pText = "";
  35.    
  36.  /*
  37.     //
  38.     */
  39.       public static final String ALGORITHM = "RSA";
  40.  
  41.   /**
  42.    * String to hold the name of the private key file.
  43.    */
  44.   public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
  45.  
  46.   /**
  47.    * String to hold name of the public key file.
  48.    */
  49.   public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
  50.  
  51.   /**
  52.    * Generate key which contains a pair of private and public key using 1024
  53.    * bytes. Store the set of keys in Prvate.key and Public.key files.
  54.    *
  55.    * @throws NoSuchAlgorithmException
  56.    * @throws IOException
  57.    * @throws FileNotFoundException
  58.    */
  59.   public static void generateKey() {
  60.     try {
  61.       final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
  62.       keyGen.initialize(1024);
  63.       final KeyPair key = keyGen.generateKeyPair();
  64.  
  65.       File privateKeyFile = new File(PRIVATE_KEY_FILE);
  66.       File publicKeyFile = new File(PUBLIC_KEY_FILE);
  67.  
  68.       // Create files to store public and private key
  69.       if (privateKeyFile.getParentFile() != null) {
  70.         privateKeyFile.getParentFile().mkdirs();
  71.       }
  72.       privateKeyFile.createNewFile();
  73.  
  74.       if (publicKeyFile.getParentFile() != null) {
  75.         publicKeyFile.getParentFile().mkdirs();
  76.       }
  77.       publicKeyFile.createNewFile();
  78.  
  79.       // Saving the Public key in a file
  80.       ObjectOutputStream publicKeyOS = new ObjectOutputStream(
  81.           new FileOutputStream(publicKeyFile));
  82.       publicKeyOS.writeObject(key.getPublic());
  83.       publicKeyOS.close();
  84.  
  85.       // Saving the Private key in a file
  86.       ObjectOutputStream privateKeyOS = new ObjectOutputStream(
  87.           new FileOutputStream(privateKeyFile));
  88.       privateKeyOS.writeObject(key.getPrivate());
  89.       privateKeyOS.close();
  90.     } catch (Exception e) {
  91.       e.printStackTrace();
  92.     }
  93.  
  94.   }
  95.  
  96.   /**
  97.    * The method checks if the pair of public and private key has been generated.
  98.    *
  99.    * @return flag indicating if the pair of keys were generated.
  100.    */
  101.   public static boolean areKeysPresent() {
  102.  
  103.     File privateKey = new File(PRIVATE_KEY_FILE);
  104.     File publicKey = new File(PUBLIC_KEY_FILE);
  105.  
  106.     if (privateKey.exists() && publicKey.exists()) {
  107.       return true;
  108.     }
  109.     return false;
  110.   }
  111.  
  112.   /**
  113.    * Encrypt the plain text using public key.
  114.    *
  115.    * @param text
  116.    *          : original plain text
  117.    * @param key
  118.    *          :The public key
  119.    * @return Encrypted text
  120.    * @throws java.lang.Exception
  121.    */
  122.   public static byte[] encrypt(String text, PublicKey key) {
  123.     byte[] cipherText = null;
  124.     try {
  125.       // get an RSA cipher object and print the provider
  126.       final Cipher cipher = Cipher.getInstance(ALGORITHM);
  127.       // encrypt the plain text using the public key
  128.       cipher.init(Cipher.ENCRYPT_MODE, key);
  129.       cipherText = cipher.doFinal(text.getBytes());
  130.     } catch (Exception e) {
  131.       e.printStackTrace();
  132.     }
  133.     return cipherText;
  134.   }
  135.  
  136.   /**
  137.    * Decrypt text using private key.
  138.    *
  139.    * @param text
  140.    *          :encrypted text
  141.    * @param key
  142.    *          :The private key
  143.    * @return plain text
  144.    * @throws java.lang.Exception
  145.    */
  146.   public static String decrypt(byte[] text, PrivateKey key) {
  147.     byte[] dectyptedText = null;
  148.     try {
  149.       // get an RSA cipher object and print the provider
  150.       final Cipher cipher = Cipher.getInstance(ALGORITHM);
  151.       // decrypt the text using the private key
  152.       cipher.init(Cipher.DECRYPT_MODE, key);
  153.       System.out.println("Text in Decrypt"+ text);
  154.       dectyptedText = cipher.doFinal(text);
  155.  
  156.     } catch (Exception ex) {
  157.       ex.printStackTrace();
  158.       System.out.println("Blah blah: "+ex);
  159.     }
  160.     System.out.println("Decrypter Text: " +dectyptedText);
  161.     return new String(dectyptedText);
  162.   }
  163.  
  164.    
  165.     /**
  166.      * Creates new form DecryptForm
  167.      */
  168.     public DecryptForm() {
  169.         initComponents();
  170.     }
  171.  
  172.     /**
  173.      * This method is called from within the constructor to initialize the form.
  174.      * WARNING: Do NOT modify this code. The content of this method is always
  175.      * regenerated by the Form Editor.
  176.      */
  177.     @SuppressWarnings("unchecked")
  178.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  179.     private void initComponents() {
  180.  
  181.         jLabel1 = new javax.swing.JLabel();
  182.         dtextbox = new javax.swing.JTextField();
  183.         Dbutton = new javax.swing.JButton();
  184.         DecryptB = new javax.swing.JButton();
  185.         jLabel2 = new javax.swing.JLabel();
  186.         saveintb = new javax.swing.JTextField();
  187.         Dbutton1 = new javax.swing.JButton();
  188.  
  189.         jLabel1.setText("File");
  190.  
  191.         dtextbox.setEditable(false);
  192.  
  193.         Dbutton.setText("Browse");
  194.         Dbutton.addActionListener(new java.awt.event.ActionListener() {
  195.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  196.                 DbuttonActionPerformed(evt);
  197.             }
  198.         });
  199.  
  200.         DecryptB.setText("DeCrypt");
  201.         DecryptB.addActionListener(new java.awt.event.ActionListener() {
  202.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  203.                 DecryptBActionPerformed(evt);
  204.             }
  205.         });
  206.  
  207.         jLabel2.setText("Save In");
  208.  
  209.         saveintb.setEditable(false);
  210.  
  211.         Dbutton1.setText("Browse");
  212.         Dbutton1.addActionListener(new java.awt.event.ActionListener() {
  213.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  214.                 Dbutton1ActionPerformed(evt);
  215.             }
  216.         });
  217.  
  218.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  219.         getContentPane().setLayout(layout);
  220.         layout.setHorizontalGroup(
  221.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  222.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  223.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  224.                     .addGroup(layout.createSequentialGroup()
  225.                         .addGap(71, 71, 71)
  226.                         .addComponent(saveintb)
  227.                         .addGap(10, 10, 10)
  228.                         .addComponent(Dbutton1))
  229.                     .addGroup(layout.createSequentialGroup()
  230.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  231.                             .addGroup(layout.createSequentialGroup()
  232.                                 .addContainerGap(218, Short.MAX_VALUE)
  233.                                 .addComponent(DecryptB))
  234.                             .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
  235.                                 .addGap(24, 24, 24)
  236.                                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  237.                                     .addComponent(jLabel2)
  238.                                     .addComponent(jLabel1))
  239.                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  240.                                 .addComponent(dtextbox)))
  241.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  242.                         .addComponent(Dbutton)))
  243.                 .addGap(26, 26, 26))
  244.         );
  245.         layout.setVerticalGroup(
  246.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  247.             .addGroup(layout.createSequentialGroup()
  248.                 .addGap(48, 48, 48)
  249.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  250.                     .addComponent(jLabel1)
  251.                     .addComponent(dtextbox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  252.                     .addComponent(Dbutton))
  253.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  254.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  255.                     .addComponent(jLabel2)
  256.                     .addComponent(saveintb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  257.                     .addComponent(Dbutton1))
  258.                 .addGap(30, 30, 30)
  259.                 .addComponent(DecryptB)
  260.                 .addContainerGap(120, Short.MAX_VALUE))
  261.         );
  262.  
  263.         pack();
  264.     }// </editor-fold>                        
  265.  
  266.     private void DbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                        
  267.  
  268.     // TODO add your handling code here:
  269.         JFileChooser chooser = new JFileChooser();
  270.         chooser.showOpenDialog(null);
  271.         File f = chooser.getSelectedFile();
  272.         filename = f.getAbsolutePath();
  273.         dtextbox.setText(filename);
  274.        
  275.         //String ext="";
  276.         //int mid= filename.lastIndexOf(".");      
  277.         //ext=filename.substring(mid+1,filename.length());  
  278.         //System.out.println("Extension ="+ext);
  279.         //JOptionPane.showConfirmDialog(null, ext);
  280.     }                                      
  281.  
  282.     private void DecryptBActionPerformed(java.awt.event.ActionEvent evt) {                                        
  283.         // TODO add your handling code here:
  284.         final String plainText;
  285.         if (!areKeysPresent()) {
  286.         // Method generates a pair of keys using the RSA algorithm and stores it
  287.         // in their respective files
  288.         generateKey();
  289.       }
  290.         if(dtextbox.getText().equals(""))
  291.         {
  292.             final JPanel panel = new JPanel();
  293.             JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);
  294.             //JOptionPane.showMessageDialog(JOptionPane.ERROR_MESSAGE, "Error: No File Selected");
  295.             return;
  296.         }
  297.         /*if(saveintb.getText().equals(""))
  298.         {
  299.             final JPanel panel = new JPanel();
  300.             JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);
  301.             //JOptionPane.showMessageDialog(JOptionPane.ERROR_MESSAGE, "Error: No File Selected");
  302.             return;
  303.         }*/
  304.         String ext="";
  305.         int mid= filename.lastIndexOf(".");      
  306.         ext=filename.substring(mid+1,filename.length());
  307.         String fileString = "";
  308.         try {                                        
  309.             // TODO add your handling code here:
  310.             int i;
  311.             FileInputStream fin = null;
  312.             try {
  313.                 fin = new FileInputStream(filename);
  314.             } catch (FileNotFoundException ex) {
  315.                 Logger.getLogger(EncryptForm.class.getName()).log(Level.SEVERE, null, ex);
  316.             }
  317.             do{
  318.                 i=fin.read();
  319.                 if(i!=-1)
  320.                 {
  321.                     fileString +=(char) i;
  322.                 }
  323.             }while(i!=-1);
  324.             fin.close();
  325.             //JOptionPane.showMessageDialog(null, fileString);
  326.         } catch (IOException ex) {
  327.         Logger.getLogger(EncryptForm.class.getName()).log(Level.SEVERE, null, ex);
  328.         }
  329.         byte[] bytes = fileString.getBytes();
  330.         System.out.println("String to Bytes0: "+bytes);
  331.         if(ext.equals("RSA"))
  332.         {
  333.             try {
  334.                 ObjectInputStream inputStream;
  335.                
  336.                
  337.                 inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
  338.                 final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
  339.                 byte[] byteData = fileString.getBytes();
  340.                 JOptionPane.showMessageDialog(null, byteData);
  341.                
  342.                 try
  343.                 {    
  344.                    JOptionPane.showMessageDialog(null, privateKey);
  345.                    System.out.println("Private key: "+privateKey);
  346.                     plainText = decrypt(byteData, privateKey);
  347.                 }
  348.                 catch(Exception ex)
  349.                 {
  350.                     System.out.println(ex);
  351.                     JOptionPane.showMessageDialog(null, ex);
  352.                 }
  353.                 pText = plainText;
  354.             } catch (IOException | ClassNotFoundException ex) {
  355.                 Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
  356.             }
  357.             JOptionPane.showMessageDialog(null, "RSA Decryption Complete");
  358.         }
  359.         FileOutputStream fop = null;
  360.     File file;  
  361.     try {  
  362.         file = new File("c:\\JavaFiles\\dfile.txt");           
  363.         fop = new FileOutputStream(file);          
  364. // if file doesnt exists, then create it
  365.            
  366.         if (!file.exists()) {              
  367.             file.createNewFile();          
  368.         }
  369.  // get the content in bytes                   
  370.         byte[] contentInBytes = pText.getBytes();          
  371.         fop.write(contentInBytes);         
  372.         fop.flush();           
  373.         fop.close();
  374.     } catch (IOException e) {
  375.         e.printStackTrace();
  376.     } finally {
  377.         try {
  378.             if (fop != null) {
  379.                 fop.close();           
  380.                         }      
  381.                 } catch (IOException e) {          
  382.                     e.printStackTrace();       
  383.                 }
  384.     }//RSA Ends
  385.     }                                        
  386.  
  387.     private void Dbutton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  388.         // TODO add your handling code here:
  389.         JFileChooser chooser = new JFileChooser();
  390.         chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  391.         int returnVal = chooser.showOpenDialog(null);
  392.         if(returnVal == JFileChooser.APPROVE_OPTION) {
  393.         saveintb.setText(chooser.getSelectedFile().getAbsolutePath());
  394.         }
  395.     }                                        
  396.  
  397.  
  398.     // Variables declaration - do not modify                    
  399.     private javax.swing.JButton Dbutton;
  400.     private javax.swing.JButton Dbutton1;
  401.     private javax.swing.JButton DecryptB;
  402.     private javax.swing.JTextField dtextbox;
  403.     private javax.swing.JLabel jLabel1;
  404.     private javax.swing.JLabel jLabel2;
  405.     private javax.swing.JTextField saveintb;
  406.     // End of variables declaration                  
  407. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement