我有一个用于加密文本的系统,但是我试图创建一个用于解密文本的系统,但是它不起作用。系统是:
将加密的文本初始化为字节[]
使用加密的文本初始化解密的文本
他只返回加密的文本,而不返回解密的文本。您有调试的想法吗?
谢谢。
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;
}
答案 0 :(得分:2)
您可以使用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
测试
答案 1 :(得分:0)
我使用jasypt来加密密码。该方法非常简单。
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword("some_Password_Maybe_generated_At_random");
...
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);
通常我不会将密码放在 source 中,而是将其保存在用户主目录中的文件中。
加密与用户主目录安全和私有一样强大。
此方法很好,因为它返回可以放入配置文件中的字符串。
正如我之前所说,它不是非常是安全的,只要 encryption password 是安全的,它将保护加密的文本。