[英]AES encryption - how to later decrypt the encrypted string?
我有一個Java程序。 這是AES加密-解密程序。 該程序具有圖形用戶界面,可以輸入字符串並顯示AES加密的字符串。 該程序還使用代碼中編寫的解密功能顯示原始字符串。 界面是這樣的:當輸入字符串並單擊轉換按鈕時,加密和解密的結果顯示在面板中。 這是程序。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AESGUI extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("AES Encryption");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600,300));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
AESGUI p = new AESGUI();
frame.getContentPane().add(p);
frame.pack();
frame.setVisible(true);
}
private JTextField in;
private JTextArea out;
public AESGUI() {
JLabel info = new JLabel("Type any String");
in = new JTextField(20);
JButton encrypt = new JButton("Encrypt");
out = new JTextArea(10,40);
out.setEditable(false);
encrypt.addActionListener(new encryptListener());
in.addActionListener(new encryptListener());
add(info);
add(in);
add(encrypt);
add(out);
add(new JScrollPane(out));
}
private class encryptListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String data = in.getText();
if (data.length() == 0) { }
else
try {
String en = encrypt(data);
out.append("Encrypted string: " + en + "\n");
out.append("Original String: " + decrypt(en) + "\n\n");
} catch(Exception ex) { }
}
}
public String asHex(byte[] buf) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
private SecretKeySpec skeySpec;
private Cipher cipher;
private byte[] encrypted;
public String encrypt(String str) throws Exception {
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(str.getBytes());
return asHex(encrypted);
}
public String decrypt(String str) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
return originalString;
}
}
該程序不會告訴用戶使用哪個密鑰來加密字符串。 由於它不會將密鑰告訴用戶,因此用戶以后無法解密加密的字符串。 程序以十六進制編碼顯示加密的字符串。 為了以后解密該字符串,最好是更改程序,以便該程序基於密碼創建一個秘密密鑰,或者更改該程序以向用戶顯示隨機生成的秘密密鑰更好,他可以使用該密鑰以后解密字符串?
如果該用戶是實際的最終用戶,而該用戶將在以后的某個時間點使用加密密鑰解密加密的數據,則我看不到為用戶顯示密鑰有任何問題。
您還可以選擇通過密碼生成加密密鑰的第一個選項,但是在這種情況下,如果您希望用戶稍后再解密數據,則需要再次讓他輸入加密密碼並生成加密密鑰(還要確保它會產生sme密鑰)並吸引用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.