Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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 Encrypt;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.JFileChooser;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.util.Arrays;
- import javax.crypto.Cipher;
- /**
- *
- * @author Proking
- */
- public class DecryptForm extends javax.swing.JInternalFrame {
- String filename = "";
- String pText = "";
- /*
- //
- */
- public static final String ALGORITHM = "RSA";
- /**
- * String to hold the name of the private key file.
- */
- public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
- /**
- * String to hold name of the public key file.
- */
- public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
- /**
- * Generate key which contains a pair of private and public key using 1024
- * bytes. Store the set of keys in Prvate.key and Public.key files.
- *
- * @throws NoSuchAlgorithmException
- * @throws IOException
- * @throws FileNotFoundException
- */
- public static void generateKey() {
- try {
- final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
- keyGen.initialize(1024);
- final KeyPair key = keyGen.generateKeyPair();
- File privateKeyFile = new File(PRIVATE_KEY_FILE);
- File publicKeyFile = new File(PUBLIC_KEY_FILE);
- // Create files to store public and private key
- if (privateKeyFile.getParentFile() != null) {
- privateKeyFile.getParentFile().mkdirs();
- }
- privateKeyFile.createNewFile();
- if (publicKeyFile.getParentFile() != null) {
- publicKeyFile.getParentFile().mkdirs();
- }
- publicKeyFile.createNewFile();
- // Saving the Public key in a file
- ObjectOutputStream publicKeyOS = new ObjectOutputStream(
- new FileOutputStream(publicKeyFile));
- publicKeyOS.writeObject(key.getPublic());
- publicKeyOS.close();
- // Saving the Private key in a file
- ObjectOutputStream privateKeyOS = new ObjectOutputStream(
- new FileOutputStream(privateKeyFile));
- privateKeyOS.writeObject(key.getPrivate());
- privateKeyOS.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * The method checks if the pair of public and private key has been generated.
- *
- * @return flag indicating if the pair of keys were generated.
- */
- public static boolean areKeysPresent() {
- File privateKey = new File(PRIVATE_KEY_FILE);
- File publicKey = new File(PUBLIC_KEY_FILE);
- if (privateKey.exists() && publicKey.exists()) {
- return true;
- }
- return false;
- }
- /**
- * Encrypt the plain text using public key.
- *
- * @param text
- * : original plain text
- * @param key
- * :The public key
- * @return Encrypted text
- * @throws java.lang.Exception
- */
- public static byte[] encrypt(String text, PublicKey key) {
- byte[] cipherText = null;
- try {
- // get an RSA cipher object and print the provider
- final Cipher cipher = Cipher.getInstance(ALGORITHM);
- // encrypt the plain text using the public key
- cipher.init(Cipher.ENCRYPT_MODE, key);
- cipherText = cipher.doFinal(text.getBytes());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return cipherText;
- }
- /**
- * Decrypt text using private key.
- *
- * @param text
- * :encrypted text
- * @param key
- * :The private key
- * @return plain text
- * @throws java.lang.Exception
- */
- public static String decrypt(byte[] text, PrivateKey key) {
- byte[] dectyptedText = null;
- try {
- // get an RSA cipher object and print the provider
- final Cipher cipher = Cipher.getInstance(ALGORITHM);
- // decrypt the text using the private key
- cipher.init(Cipher.DECRYPT_MODE, key);
- System.out.println("Text in Decrypt"+ text);
- dectyptedText = cipher.doFinal(text);
- } catch (Exception ex) {
- ex.printStackTrace();
- System.out.println("Blah blah: "+ex);
- }
- System.out.println("Decrypter Text: " +dectyptedText);
- return new String(dectyptedText);
- }
- /**
- * Creates new form DecryptForm
- */
- public DecryptForm() {
- initComponents();
- }
- /**
- * 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">
- private void initComponents() {
- jLabel1 = new javax.swing.JLabel();
- dtextbox = new javax.swing.JTextField();
- Dbutton = new javax.swing.JButton();
- DecryptB = new javax.swing.JButton();
- jLabel2 = new javax.swing.JLabel();
- saveintb = new javax.swing.JTextField();
- Dbutton1 = new javax.swing.JButton();
- jLabel1.setText("File");
- dtextbox.setEditable(false);
- Dbutton.setText("Browse");
- Dbutton.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- DbuttonActionPerformed(evt);
- }
- });
- DecryptB.setText("DeCrypt");
- DecryptB.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- DecryptBActionPerformed(evt);
- }
- });
- jLabel2.setText("Save In");
- saveintb.setEditable(false);
- Dbutton1.setText("Browse");
- Dbutton1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- Dbutton1ActionPerformed(evt);
- }
- });
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
- getContentPane().setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
- .addGroup(layout.createSequentialGroup()
- .addGap(71, 71, 71)
- .addComponent(saveintb)
- .addGap(10, 10, 10)
- .addComponent(Dbutton1))
- .addGroup(layout.createSequentialGroup()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
- .addGroup(layout.createSequentialGroup()
- .addContainerGap(218, Short.MAX_VALUE)
- .addComponent(DecryptB))
- .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
- .addGap(24, 24, 24)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
- .addComponent(jLabel2)
- .addComponent(jLabel1))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(dtextbox)))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(Dbutton)))
- .addGap(26, 26, 26))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(48, 48, 48)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jLabel1)
- .addComponent(dtextbox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(Dbutton))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jLabel2)
- .addComponent(saveintb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(Dbutton1))
- .addGap(30, 30, 30)
- .addComponent(DecryptB)
- .addContainerGap(120, Short.MAX_VALUE))
- );
- pack();
- }// </editor-fold>
- private void DbuttonActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- JFileChooser chooser = new JFileChooser();
- chooser.showOpenDialog(null);
- File f = chooser.getSelectedFile();
- filename = f.getAbsolutePath();
- dtextbox.setText(filename);
- //String ext="";
- //int mid= filename.lastIndexOf(".");
- //ext=filename.substring(mid+1,filename.length());
- //System.out.println("Extension ="+ext);
- //JOptionPane.showConfirmDialog(null, ext);
- }
- private void DecryptBActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- final String plainText;
- if (!areKeysPresent()) {
- // Method generates a pair of keys using the RSA algorithm and stores it
- // in their respective files
- generateKey();
- }
- if(dtextbox.getText().equals(""))
- {
- final JPanel panel = new JPanel();
- JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);
- //JOptionPane.showMessageDialog(JOptionPane.ERROR_MESSAGE, "Error: No File Selected");
- return;
- }
- /*if(saveintb.getText().equals(""))
- {
- final JPanel panel = new JPanel();
- JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);
- //JOptionPane.showMessageDialog(JOptionPane.ERROR_MESSAGE, "Error: No File Selected");
- return;
- }*/
- String ext="";
- int mid= filename.lastIndexOf(".");
- ext=filename.substring(mid+1,filename.length());
- String fileString = "";
- try {
- // TODO add your handling code here:
- int i;
- FileInputStream fin = null;
- try {
- fin = new FileInputStream(filename);
- } catch (FileNotFoundException ex) {
- Logger.getLogger(EncryptForm.class.getName()).log(Level.SEVERE, null, ex);
- }
- do{
- i=fin.read();
- if(i!=-1)
- {
- fileString +=(char) i;
- }
- }while(i!=-1);
- fin.close();
- //JOptionPane.showMessageDialog(null, fileString);
- } catch (IOException ex) {
- Logger.getLogger(EncryptForm.class.getName()).log(Level.SEVERE, null, ex);
- }
- byte[] bytes = fileString.getBytes();
- System.out.println("String to Bytes0: "+bytes);
- if(ext.equals("RSA"))
- {
- try {
- ObjectInputStream inputStream;
- inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
- final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
- byte[] byteData = fileString.getBytes();
- JOptionPane.showMessageDialog(null, byteData);
- try
- {
- JOptionPane.showMessageDialog(null, privateKey);
- System.out.println("Private key: "+privateKey);
- plainText = decrypt(byteData, privateKey);
- }
- catch(Exception ex)
- {
- System.out.println(ex);
- JOptionPane.showMessageDialog(null, ex);
- }
- pText = plainText;
- } catch (IOException | ClassNotFoundException ex) {
- Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
- }
- JOptionPane.showMessageDialog(null, "RSA Decryption Complete");
- }
- FileOutputStream fop = null;
- File file;
- try {
- file = new File("c:\\JavaFiles\\dfile.txt");
- fop = new FileOutputStream(file);
- // if file doesnt exists, then create it
- if (!file.exists()) {
- file.createNewFile();
- }
- // get the content in bytes
- byte[] contentInBytes = pText.getBytes();
- fop.write(contentInBytes);
- fop.flush();
- fop.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (fop != null) {
- fop.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }//RSA Ends
- }
- private void Dbutton1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- JFileChooser chooser = new JFileChooser();
- chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
- int returnVal = chooser.showOpenDialog(null);
- if(returnVal == JFileChooser.APPROVE_OPTION) {
- saveintb.setText(chooser.getSelectedFile().getAbsolutePath());
- }
- }
- // Variables declaration - do not modify
- private javax.swing.JButton Dbutton;
- private javax.swing.JButton Dbutton1;
- private javax.swing.JButton DecryptB;
- private javax.swing.JTextField dtextbox;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JTextField saveintb;
- // End of variables declaration
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement