使用AES的Java加密

尼采斯库·卢西安(Nitescu Lucian)

我正在尝试使用AES类创建一个加密系统:

package Source;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
  static String IV = "AAAAAAAAAAAAAAAA";
  static String plaintext = "test text 123\0\0\0"; /*Note null padding*/
  static String encryptionKey = "H4tch4repratygonetowil5h4kers";
  public static void main(String [] args) {
    try {

      System.out.println("==Java==");
      System.out.println("plain:   " + plaintext);

      byte[] cipher = encrypt(plaintext, encryptionKey);

      System.out.print("cipher:  ");
      for (int i=0; i<cipher.length; i++)
        System.out.print(new Integer(cipher[i])+" ");
      System.out.println("");

      String decrypted = decrypt(cipher, encryptionKey);

      System.out.println("decrypt: " + decrypted);

    } catch (Exception e) {
      e.printStackTrace();
    } 
  }

  public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
  }

  private static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    return new String(cipher.doFinal(cipherText),"UTF-8");
  }
}

这是我的代码实现:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;


import Source.AES;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;

public class first {

    private JFrame frame;
    private JPasswordField passwordField;
    private JTextArea txtrEnterTextHere;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    first window = new first();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public first() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JOptionPane.showMessageDialog(null, "Welcome to Encryption System! ");
        JButton btnNewButton = new JButton("Send Info");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String text = txtrEnterTextHere.getText();
                String pass = passwordField.getText();
                String str = null;
                try {
                    str = new String(AES.encrypt(text, pass));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                txtrEnterTextHere.setText(str);

                JOptionPane.showMessageDialog(null, "Your intel has been encrypted!");

            }
        });
        frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);

        passwordField = new JPasswordField();
        frame.getContentPane().add(passwordField, BorderLayout.SOUTH);

        txtrEnterTextHere = new JTextArea();
        txtrEnterTextHere.setText("ENTER TEXT HERE AND PASSWORD BELLOW!");

        frame.getContentPane().add(txtrEnterTextHere, BorderLayout.CENTER);
    }

}

如何使变量“ str”实际具有加密文本的值?在运行时出现错误,并且有一个空字段……可以将byte []更改为字符串吗?

更新错误:

java.lang.IllegalArgumentException:Source.AES.encrypt(AES.java:41)处的javax.crypto.spec.SecretKeySpec。(SecretKeySpec.java:96)处的空键位于第一个$ 2.actionPerformed(first.java:62)处javax.swing.DefaultButtonModel.setPressed(未知源)处的javax.swing.DefaultButtonModel.fireActionPerformed(未知源)处的javax.swing.AbstractButton $ Handler.actionPerformed(未知源)处的javax.swing.DefaultButtonModel.setPressed(未知源)处的javax.swing.AbstractButton $ Handler.actionPerformed(未知源)处javax.swing.JComponent.processMouseEvent(未知源)处的javax.swing.JComponent.processMouseEvent(未知源)处的javax.swing.plaf.basic.BasicButtonListener.mouseReleased(未知源)处java.awt.Component.processEvent(未知源)处),位于java.awt.Container.java.awt.Component.dispatchEventImpl(未知源)的java.awt.Container.processEvent(未知源)。java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)处java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)处java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)处java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) java.awt.Container.dispatchEventImpl上的未知源(java.awt.Window.dispatchEventImpl上的java.awt.Component.dispatchEventImpl的未知源(java.awt.EventQueue.dispatchEventImpl上的未知源) )在java.awt.EventQueue.access $ 500(未知源)在java.awt.EventQueue $ 3.run(未知源)在java.awt.EventQueue $ 3.run(未知源)在java.security.AccessController.doPrivileged(本机java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(方法)处的方法)。Java的ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知的源),java.awt.EventQueue $ 4.run(未知的源),java.security.AccessController.doPrivileged(本机方法),java.awt.EventQueue $ 4.run(未知的源)。 security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知源)在java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)在java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)在java.awt.EventDispatchThread.pumpEventsForFilter(未知源) awt.EventDispatchThread.pumpEventsForHierarchy(未知源)在java.awt.EventDispatchThread.pumpEvents(未知源)在java.awt.EventDispatchThread.pumpEvents(未知源)在java.awt.EventDispatchThread.run(未知源)EventQueue $ 4.run(未知源),位于java.security.AccessController.doPrivileged(本机方法),位于java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知源),位于java.awt.EventQueue.dispatchEvent(未知源),位于java.awt java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)java.awt.EventDispatchThread.pumpEventsForFilter(未知源)java.awt.EventDispatchThread.pumpEvents(未知源)java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源) java.awt.EventDispatchThread.run上的.pumpEvents(未知源)(未知源)EventQueue $ 4.run(未知源),位于java.security.AccessController.doPrivileged(本机方法),位于java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知源),位于java.awt.EventQueue.dispatchEvent(未知源),位于java.awt java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)java.awt.EventDispatchThread.pumpEventsForFilter(未知源)java.awt.EventDispatchThread.pumpEvents(未知源)java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源) java.awt.EventDispatchThread.run上的.pumpEvents(未知源)(未知源)java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)上的dispatchEvent(未知源)java.awt.EventDispatchThread.pumpEventsForFilter(未知源)处java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源) java.awt.EventDispatchThread.pumpEvents(源未知)(java.awt.EventDispatchThread.run中的未知源)java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)上的dispatchEvent(未知源)java.awt.EventDispatchThread.pumpEventsForFilter(未知源)处java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源) java.awt.EventDispatchThread.pumpEvents(源未知)(java.awt.EventDispatchThread.run中的未知源)

格里莎·温特劳布(Grisha Weintraub)

您在这里遇到几个问题。

  1. 您有Empty key at javax.crypto.spec.SecretKeySpec例外,因为您没有输入任何密码。

  2. 输入密码后,您将遇到类似的异常Invalid AES key length: 8 bytes,因为密钥应为特定长度(有关更多信息,请参见此处)。

  3. 使用哈希值生成密钥后,您将遇到以下异常- javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes,因为您的加密模式不使用填充。您可以将其更改为AES/CBC/PKCS5Padding

最后,使用以下“加密”方法,您将获得所需的内容:

public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    byte [] hashedPassword = sha.digest(encryptionKey.getBytes("UTF-8"));
    hashedPassword = Arrays.copyOf(hashedPassword, 16);
    SecretKeySpec key = new SecretKeySpec(hashedPassword, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}

(*)当然,为了解密消息,您还必须在“ decrypt”方法中进行类似的更改...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章