0

我有两个服务实例,它们在云中运行加密和解密。解密有时会因“解密失败”错误而失败。我猜这是因为每个实例都有自己的 Aead 实例。我该如何解决这个问题?

    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"));
    }

如果只有一个实例正在运行,我会得到一致的结果......

4

2 回答 2

1

我将不得不使用相同的密钥集来加密和解密。我可以通过将密钥集存储在物理位置并使用它来创建 Aead 实例来解决此问题。通过此更改,我的服务的所有实例都能够成功解密字符串

于 2019-04-15T21:47:51.857 回答
0

看起来像一个线程安全问题。尝试使 getInstance 同步。此外,保护对私有 Aead aead的访问

如果您不小心,多个线程可能会改变 aead 的状态。

考虑使用队列来完成您的工作,或同步访问与 aead 交互的内容。

于 2019-04-15T15:25:46.700 回答