Java 解密结果不一致
我有两个在云中运行的加密和解密服务实例。有时解密失败,出现“解密失败”错误。我猜这是因为每个实例都有自己的Aead实例。我如何解决这个问题Java 解密结果不一致,java,tink,Java,Tink,我有两个在云中运行的加密和解密服务实例。有时解密失败,出现“解密失败”错误。我猜这是因为每个实例都有自己的Aead实例。我如何解决这个问题 public class Utils { private static final Logger log = LoggerFactory.getLogger(Utils.class); private Aead aead; private static Utils utils; pri
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
private Aead aead;
private static Utils utils;
private Utils() {
try {
AeadConfig.register();
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
aead = AeadFactory.getPrimitive(keysetHandle);
} catch (GeneralSecurityException e) {
log.error(String.format("Error occured: %s",e.getMessage())).log();
}
}
public static Utils getInstance() {
if(null == utils) {
utils = new Utils();
}
return utils;
}
public String encrypt(String text) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] plainText = text.getBytes("ISO-8859-1");
byte[] additionalData = null;
byte[] cipherText = aead.encrypt(plainText,additionalData);
String output = Base64.getEncoder().encodeToString(cipherText);
return output;
}
public String decrypt(String text) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] cipherText = Base64.getDecoder().decode(text);
byte[] additionalData = null;
byte[] decipheredData = aead.decrypt(cipherText,additionalData);
String output = new String(decipheredData,"ISO-8859-1");
return output;
}
@Test
public void encrypt() throws IOException, GeneralSecurityException {
String encryptedText = cryptographicUtils.encrypt("Hello World");
assertThat(encryptedText, Matchers.notNullValue());
}
@Test
public void decrypt() throws IOException, GeneralSecurityException {
String encryptedText = cryptographicUtils.encrypt("Hello 123456");
String decrypedText = cryptographicUtils.decrypt(encryptedText);
assertThat(decrypedText, Matchers.is("Hello 123456"));
}
如果只有一个实例在运行,我会得到一致的结果…看起来像是线程安全问题。尝试使getInstance同步。此外,保护对专用Aead Aead的访问 如果不小心,多个线程可能会改变aead的状态
考虑一个队列来完成您的工作,或者同步访问与aead交互的内容。我必须使用相同的密钥集来加密和解密。我可以通过将密钥集存储在物理位置并使用它创建Aead实例来解决这个问题。通过此更改,我的服务的所有实例都能够成功解密字符串