By GokiSoft.com| 10:03 25/09/2021|
Java Advanced

[Share Code] Tìm hiểu mã hoá Cipher - Lập trình Java nâng cao. C2009G

#CipherFrame.java


/*
 * 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 lesson11;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Diep.Tran
 */
public class CipherFrame extends javax.swing.JFrame {

    /**
     * Creates new form CipherFrame
     */
    public CipherFrame() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        originalTxt = new javax.swing.JTextArea();
        encryptedBtn = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        encryptedTxt = new javax.swing.JTextArea();
        decryptedBtn = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        decryptedTxt = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        originalTxt.setColumns(20);
        originalTxt.setRows(5);
        jScrollPane1.setViewportView(originalTxt);

        encryptedBtn.setText("Ma Hoa");
        encryptedBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                encryptedBtnActionPerformed(evt);
            }
        });

        encryptedTxt.setColumns(20);
        encryptedTxt.setRows(5);
        jScrollPane2.setViewportView(encryptedTxt);

        decryptedBtn.setText("Giai Ma");
        decryptedBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                decryptedBtnActionPerformed(evt);
            }
        });

        decryptedTxt.setColumns(20);
        decryptedTxt.setRows(5);
        jScrollPane3.setViewportView(decryptedTxt);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                    .addComponent(encryptedBtn)
                    .addComponent(jScrollPane2)
                    .addComponent(decryptedBtn)
                    .addComponent(jScrollPane3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(encryptedBtn)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(decryptedBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void encryptedBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_encryptedBtnActionPerformed
        // TODO add your handling code here:
        String line = originalTxt.getText();
        String encrypted = mahoa(line);
        encryptedTxt.setText(encrypted);
    }//GEN-LAST:event_encryptedBtnActionPerformed

    private void decryptedBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decryptedBtnActionPerformed
        // TODO add your handling code here:
        String encrypted = encryptedTxt.getText();
        String data = giaima(encrypted);
        decryptedTxt.setText(data);
    }//GEN-LAST:event_decryptedBtnActionPerformed

    private String giaima(String str) {
        try {
            String SECRET_KEY = "gokisoft.com1234";//Yeu cau do dai 16 ky tu.
            SecretKeySpec skeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            
            byte[] byteEncrypted = Base64.getDecoder().decode(str);

            byte[] byteDecrypted = cipher.doFinal(byteEncrypted);
            String decrypted = new String(byteDecrypted);
            
            return decrypted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String mahoa(String original) {
        try {
            String SECRET_KEY = "gokisoft.com1234";//Yeu cau do dai 16 ky tu.
            SecretKeySpec skeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] byteEncrypted = cipher.doFinal(original.getBytes());
            String encrypted = Base64.getEncoder().encodeToString(byteEncrypted);

            return encrypted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * @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(CipherFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CipherFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CipherFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CipherFrame.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 CipherFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton decryptedBtn;
    private javax.swing.JTextArea decryptedTxt;
    private javax.swing.JButton encryptedBtn;
    private javax.swing.JTextArea encryptedTxt;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea originalTxt;
    // End of variables declaration//GEN-END:variables
}


#Main.java


/*
 * 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 lesson11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(reader);
        
        System.out.println("Nhap chuoi goc: ");
        String line = bufferedReader.readLine();
        
        String encrypted = mahoa(line);
        System.out.println(encrypted);
        
        String decrypted = giaima(encrypted);
        System.out.println(decrypted);
    }
    
    static String giaima(String str) {
        try {
            String SECRET_KEY = "gokisoft.com1234";//Yeu cau do dai 16 ky tu.
            SecretKeySpec skeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            
            byte[] byteEncrypted = Base64.getDecoder().decode(str);

            byte[] byteDecrypted = cipher.doFinal(byteEncrypted);
            String decrypted = new String(byteDecrypted);
            
            return decrypted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static String mahoa(String original) {
        try {
            String SECRET_KEY = "gokisoft.com1234";//Yeu cau do dai 16 ky tu.
            SecretKeySpec skeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] byteEncrypted = cipher.doFinal(original.getBytes());
            String encrypted = Base64.getEncoder().encodeToString(byteEncrypted);

            return encrypted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


Tags:



Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó