我为 AES 加密和解密编写了一个小测试用例。计划是从文件中读取一些文本,用密钥对其进行加密并再次解密。现在的问题是,文本总是相同的,错误的密码不会导致无法读取的文本。
代码中的问题在哪里,还是我犯了一个根本性错误?
主.java
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
new Main();
}
public Main() throws Exception {
Reader reader = new Reader();
String text = reader.readFile("/home/benjamin/Test.txt");
System.out.println("Original text before encryption: " + text);
// User A verschlüsselt und speichert ab
Crypto crypto = new Crypto();
SecretKeySpec secretkey = crypto.generateSecretKey("123456aA");
byte[] encryptedtext = crypto.encrypt(text, secretkey);
// User B lädt Datei und kennt das Passwort
Crypto crypto2 = new Crypto();
SecretKeySpec secretkey2 = crypto2.generateSecretKey("1kkk23456aAjbhhjbhjb");
byte[] decryptedtext = crypto2.decrypt(encryptedtext, secretkey2);
System.out.println("Original text after encryption: " + new String(decryptedtext, "UTF-8"));
}
}
加密.java
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Crypto {
public SecretKeySpec generateSecretKey(String password) throws Exception {
MessageDigest shahash = MessageDigest.getInstance("SHA-1");
byte[] key = shahash.digest();
key = Arrays.copyOf(key, 16);
return new SecretKeySpec(key, "AES");
}
public byte[] encrypt(String text, SecretKeySpec secretkey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
return cipher.doFinal(text.getBytes());
}
public byte[] decrypt(byte[] encryptedtext, SecretKeySpec secretkey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretkey);
return cipher.doFinal(encryptedtext);
}
}