如何解决如何在Java中使用AES 256 GCM模式正确加密文本?
首先,我想提一提的是,我已经研究了与加密相关的所有其他问题,因此这是一个独特的问题,不能以任何形式重复。
我已经解决这个问题了三天了,我终于得到了一段加密的代码,但是我怀疑这种加密是正确的,因为加密的文本太短,也就是说哪些在线解密工具告诉我如何,因为我希望使用独立工具(通过向另一方提供密钥)来完成解密,所以这些是我尝试使用的工具,它们都在同一件事上达成共识:{{1 }}。
我拥有的代码很简单,就像我尝试制作的那样:
The provided data/text is too small
此行用于调试:
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;
public class DataEncrypt {
//static String plainText = "This is a plain text which need to be encrypted by Java AES 256 GCM Encryption Algorithm";
public static final int AES_KEY_SIZE = 256;
public static final int GCM_IV_LENGTH = 12;
public static final int GCM_TAG_LENGTH = 16;
public String encrypt(byte[] plaintext)
{
String res=null;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(AES_KEY_SIZE);
// Generate Key
SecretKey key = keyGenerator.generateKey();
byte[] IV = new byte[GCM_IV_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(IV);
// Get Cipher Instance
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
// Create SecretKeySpec
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(),"AES");
// Create GCMParameterSpec
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8,IV);
// Initialize Cipher for ENCRYPT_MODE
cipher.init(Cipher.ENCRYPT_MODE,keySpec,gcmParameterSpec);
// Perform Encryption
byte[] cipherText = cipher.doFinal(plaintext);
res= "cipheredText= " + cipherText.toString() + "\nkeySpec=" + keySpec.toString() + "\nKey=" +
Base64.getEncoder().encodeToString(key.getEncoded());
}catch (Exception e){
}
return res;
}
}
这是我调用该函数的方式:
res= "cipheredText= " + cipherText.toString() + "\nkeySpec=" + keySpec.toString() + "\nKey=" +
Base64.getEncoder().encodeToString(key.getEncoded())
这是控制台输出:
//string number entered here is not actually the same one I used,but it has the same length
System.out.println(dataEncrypt.encrypt("320900401024111".getBytes()));
因此,我有一个密钥(来自输出),可以在联机工具中使用该密钥解密,并且我有一个加密的文本(cipheredText)要输入该工具,但是cipheredText似乎很短,或者通常是工具无法将我的原始字符串还给我(320900401024111)。
我用于解密的工具:
- https://webkit.org/demos/webcrypto/aes-gcm.html
- https://encode-decode.com/aes-256-gcm-encrypt-online/
- https://8gwifi.org/CipherFunctions.jsp
- http://aes.online-domain-tools.com/
我不是加密专家,但是我问这个问题是因为我已经竭尽全力,不是因为没有尝试,我只是需要帮助:
- 此代码是否有问题?
- 此代码的结果是否有误?
- 为什么我无法使用提到的工具解密?
谢谢您的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。