From 9c4573487a6ea9724e67421a86c3fffdf1eead20 Mon Sep 17 00:00:00 2001 From: woodser Date: Mon, 22 Sep 2025 07:32:13 -0400 Subject: [PATCH] reduce memory consumption to get encrypted payloads with hmac (#1971) --- .../java/haveno/common/crypto/Encryption.java | 26 +++---------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/common/src/main/java/haveno/common/crypto/Encryption.java b/common/src/main/java/haveno/common/crypto/Encryption.java index 93d5a527fb..6ced576950 100644 --- a/common/src/main/java/haveno/common/crypto/Encryption.java +++ b/common/src/main/java/haveno/common/crypto/Encryption.java @@ -20,7 +20,6 @@ package haveno.common.crypto; import haveno.common.util.Hex; import haveno.common.util.Utilities; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; @@ -101,36 +100,19 @@ public class Encryption { /////////////////////////////////////////////////////////////////////////////////////////// private static byte[] getPayloadWithHmac(byte[] payload, SecretKey secretKey) { - byte[] payloadWithHmac; try { - - ByteArrayOutputStream outputStream = null; - try { - byte[] hmac = getHmac(payload, secretKey); - outputStream = new ByteArrayOutputStream(); + byte[] hmac = getHmac(payload, secretKey); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(payload.length + hmac.length)) { outputStream.write(payload); outputStream.write(hmac); - outputStream.flush(); - payloadWithHmac = outputStream.toByteArray().clone(); - } catch (IOException | NoSuchProviderException e) { - log.error("Could not create hmac", e); - throw new RuntimeException("Could not create hmac"); - } finally { - if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException ignored) { - } - } + return outputStream.toByteArray(); } } catch (Throwable e) { log.error("Could not create hmac", e); - throw new RuntimeException("Could not create hmac"); + throw new RuntimeException("Could not create hmac", e); } - return payloadWithHmac; } - private static boolean verifyHmac(byte[] message, byte[] hmac, SecretKey secretKey) { try { byte[] hmacTest = getHmac(message, secretKey);