我一直在试图找出解决 Java 安全/加密库的方法,我相信我在理解正在发生的事情方面取得了一些进展。我想我设法让加密部分工作。在我的加密方法中,如果我只是尝试返回,
return new String(encryptedText, "UTF-8");
我会得到一些看起来像加密文本的不可读的混乱。当我尝试而不是返回它时,问题就出现了,继续调用decrypt 并转到明文--> 加密--> 解密这里是我所拥有的一切
import javax.crypto.*;
import java.security.*;
import java.io.UnsupportedEncodingException;
public class AES256_GCM {
public String encrypt(String cleartext) {
try
{
// encoding format needs thought
byte[] clearTextbytes = cleartext.getBytes("UTF-8");
final SecureRandom secureKeyRandomness = SecureRandom.getInstanceStrong();
final KeyGenerator AES_keyInstance = KeyGenerator.getInstance("AES");
AES_keyInstance.init(128, secureKeyRandomness);
final SecretKey secretKey = AES_keyInstance.generateKey();
final Cipher AES_cipherInstance = Cipher.getInstance("AES/GCM/NoPadding");
AES_cipherInstance.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedText = AES_cipherInstance.doFinal(clearTextbytes);
return decrypt(encryptedText, secretKey);
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | …Run Code Online (Sandbox Code Playgroud)