java - Java:我的文本解密系统不起作用
问题描述
我有一个用于加密文本的系统,但我试图创建一个用于解密文本的系统,但它不起作用。该系统是:
将加密文本初始化为 byte[]
用加密文本初始化解密文本
他只返回加密的文本,而不是解密的文本。你有调试这个的想法吗?
提前致谢。
byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
return encrypted;
}
String getDecrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
return decrypted;
}
解决方案
您在getDecrypt(...)
方法中加密加密文本。还是您想以一种方法再次对其进行加密和解密?
一种解决方案是以下代码:
package test;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Test2{
public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
System.out.println(new String(getEncrypt("test")));
System.out.println(new String(getDecrypt(getEncrypt("test"))));
}
public static byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
return encrypted;
}
public static byte [] getDecrypt(byte[] encrypted) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
return cipher.doFinal(encrypted);
}
}
输出:
�'����+~�@��@w
测试
推荐阅读
- java - 无法识别 uft 中的 java 对象
- java - Java Swing 重绘延迟
- java - jquery load() 仅在 classlevel @requestMapping("something") 时不起作用
- php - 使用连接类插入数据库命令的问题
- git - 将master重置为HEAD^而不是HEAD并提交,如何恢复?
- c++ - 使用继承属性时,派生类不采用模板基类的数据成员。为什么会这样,如何解决?
- json - 如何将logstash logback 编码器的一些方法包装到一个内部字段中?
- android - 颤动 - UI 更改仅在点击另一个元素时生效
- maven - spark-submit 无法在我的 jar 文件中使用依赖项
- r - 使用基于回归的估计器时出错