我是密码学的新手。我正在研究一个poc来加密和解密字符串。当我解密加密的字符串时,它有时会起作用,但其他时候会引发Tag不匹配错误。我错过了什么吗?
这是我的代码:
EncryptionServiceImpl.java
public class EncryptionServiceImpl {
private static final Logger log = LoggerFactory.getLogger("EncryptionServiceImpl");
private final KeysetHandle keysetHandle;
private final Aead aead;
public EncryptionServiceImpl() throws GeneralSecurityException {
AeadConfig.register();
this.keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
aead = AeadFactory.getPrimitive(keysetHandle);
}
public String encrypt(String text) throws GeneralSecurityException {
log.info(String.format("Encrypting %s", text));
byte[] plainText = text.getBytes();
byte[] additionalData = "masterkey".getBytes();
byte[] cipherText = aead.encrypt(plainText,additionalData);
String output = new String(cipherText);
log.info(String.format("The encrypted text: %s", output));
return output;
}
public String decrypt(String text) throws GeneralSecurityException {
log.info(String.format("Decrypting %s", text));
byte[] cipherText = text.getBytes();
byte[] additionalData = "masterkey".getBytes();
byte[] decipheredData = aead.decrypt(cipherText,additionalData);
String output = new String(decipheredData);
log.info(String.format("The decrypted text: %s", output));
return output;
}
}
EncryptionServiceImplTest.java
public class EncryptionServiceImplTest {
@Test
public void encrypt() throws IOException, GeneralSecurityException {
EncryptionServiceImpl encryptionService = new EncryptionServiceImpl();
String encryptedText = encryptionService.encrypt("Hello World");
assertThat(encryptedText, Matchers.notNullValue());
}
异常:信息:密文前缀与密钥匹配,但无法解密:javax.crypto.AEAD标记异常:标记不匹配!com.encryption.api.service.EncryptionService测试>解密失败
婷婷同学_
www说
富国沪深
相关分类