Search code examples
javaencryptionnetbeansjframefile-descriptor

I am encrypting and decrypting but it does not show me the decryption


I was trying to class a code that would encrypt an entered text with JFRAME, which does it well for me. Once I'm done, it saves the encrypted text in a .txt and then has to decrypt it, but I don't understand why it doesn't decrypt it for me. Thank you very much.

public class NewJFrame extends javax.swing.JFrame {
   
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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() {

        btn_Decript = new javax.swing.JButton();
        btn_Encript = new javax.swing.JButton();
        text_Encript = new javax.swing.JLabel();
        text_decript = new javax.swing.JLabel();
        Text = new javax.swing.JTextField();
        Text1 = new javax.swing.JTextField();
        Text2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btn_Decript.setText("Desencriptar");
        btn_Decript.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_DecriptActionPerformed(evt);
            }
        });

        btn_Encript.setText("Encirptar");
        btn_Encript.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_EncriptActionPerformed(evt);
            }
        });

        text_Encript.setText("Encriptat");

        text_decript.setText("Desencriptar");

        Text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TextActionPerformed(evt);
            }
        });

        Text1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Text1ActionPerformed(evt);
            }
        });

        Text2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Text2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addComponent(btn_Encript)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addComponent(btn_Decript)
                .addGap(53, 53, 53))
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addComponent(Text, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(text_Encript, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Text1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(text_decript, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Text2)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(text_Encript)
                    .addComponent(text_decript, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Text1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Text2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(46, 127, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_Encript)
                    .addComponent(btn_Decript))
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>                        

    private void TextActionPerformed(java.awt.event.ActionEvent evt) {                                     

    }                                    

    private void btn_EncriptActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Txt(encrypt(Text1.getText(), "Marti"));
        Text1.setText(llegir());
        
        Text1.setEditable(false);
    }                                           

    private void btn_DecriptActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Text2.setText(decrypt(llegir(),"Marti"));
        Text2.setText(llegir());
        
         Text1.setEditable(false);
    }                                           

    private void Text1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void Text2ActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    }                                     

    /**
     * @param args the command line arguments
     */
    
 
    // Variables declaration - do not modify                     
    private javax.swing.JTextField Text;
    private javax.swing.JTextField Text1;
    private javax.swing.JTextField Text2;
    private javax.swing.JButton btn_Decript;
    private javax.swing.JButton btn_Encript;
    private javax.swing.JLabel text_Encript;
    private javax.swing.JLabel text_decript;
    // End of variables declaration                   

    
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    
public static void Txt(String secret){
    Path path = Paths.get("./encriptar.txt");
    
    try{
        Files.writeString(path, secret, StandardCharsets.UTF_8);
    }
    catch (Exception e){
        System.out.println("Error while encrypting: ");
    }
}

public static String llegir(){
    Path path = Paths.get("./encriptar.txt");
    String algo = null;
    try{
        algo = Files.readString(path);
    }catch(Exception e){
        System.out.println("Error");
    }
    return algo;
}
  
  private static SecretKeySpec secretKey;
  private static byte[] key;
 
  
  public static void setKey(final String myKey) {
    MessageDigest sha = null;
    try {
      key = myKey.getBytes("UTF-8");
      sha = MessageDigest.getInstance("SHA-1");
      key = sha.digest(key);
      key = Arrays.copyOf(key, 16);
      secretKey = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

  public static String encrypt(final String strToEncrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      return Base64.getEncoder()
        .encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    } catch (Exception e) {
      System.out.println("Error while encrypting: ");
    }
    return null;
  }

  public static String decrypt(final String strToDecrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      return new String(cipher.doFinal(Base64.getDecoder()
        .decode(strToDecrypt)));
    } catch (Exception e) {
      System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
  } 

I try to see if someone can know how to solve the error that I write above, thanks.


Solution

  • You should really rethink you variable names

    Both actionPerfom methods are wrong:

    private void btn_EncriptActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Txt(encrypt(Text.getText(), "Marti")); //you need to use the text of field Text not from Text1
        Text1.setText(llegir());
        
        Text1.setEditable(false);
    }                                           
    
    private void btn_DecriptActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Text2.setText(decrypt(llegir(),"Marti"));
        //Text2.setText(llegir()); remove this line, it overrides the encrypted text
        
         Text2.setEditable(false);
    }                                           
    

    Take care of java naming conventions. Variable names should start with a lower case character and be camelCase not snake_case