3 回答

TA貢獻1844條經驗 獲得超8個贊
如果加密消息的字節序列存儲在字符串中,則必須使用適當的編碼。適當意味著編碼必須允許序列中的所有字節或字節組合。如果不是這種情況,則字節序列中的值會自動更改,并且在存儲期間不會被注意到。如果在解密期間從字符串重建字節數組,則原始字節數組和重建的字節數組會有所不同,并且解密將失敗。這里對此進行了很好的解釋。
由于 AES-GCM 為每個加密生成一個新的初始化向量,因此即使使用相同的明文,每個加密的加密消息也是不同的。
兩者都導致這樣一個事實,即在您的示例中,加密有時有效,有時無效:每當字節序列與您正在使用的編碼兼容時,解密就會起作用,否則就不起作用。
如果你想獨立于編碼,只需使用字節數組本身,即-method返回字節數組而不是字符串,類似地,字節數組傳遞給-method而不是字符串。encrypt
decrypt

TA貢獻1775條經驗 獲得超8個贊
我修改了代碼,但我仍然看到解密有時會因相同的請求而失敗。
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;
}
}

TA貢獻1790條經驗 獲得超9個贊
當我在本地機器中運行時,我也沒有得到代碼中的錯誤。但是當我在云(谷歌云)中部署時,我開始看到錯誤。
這是我的朱尼特代碼:
public class UtilsTest {
private static final Utils cryptographicUtils = Utils.getInstance();
@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"));
}
}
添加回答
舉報