gpt4 book ai didi

使用 AES 的 Java 加密

转载 作者:行者123 更新时间:2023-11-30 02:53:42 24 4
gpt4 key购买 nike

我正在尝试使用 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: Empty key at javax.crypto.spec.SecretKeySpec.(SecretKeySpec.java:96) at Source.AES.encrypt(AES.java:41) at first$2.actionPerformed(first.java:62) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

最佳答案

您遇到了几个问题。

  1. 由于您未输入任何密码,因此出现 Empty key at javax.crypto.spec.SecretKeySpec 异常。

  2. 输入密码后,您将遇到异常,例如无效的 AES key 长度:8 字节,因为 key 应具有特定长度(有关更多信息,请参阅 here )。

  3. 使用哈希生成 key 后,您将遇到以下异常 - 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"));
}

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

关于使用 AES 的 Java 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37877152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com