atoulme commented on a change in pull request #18: Fix memory leak.
URL: https://github.com/apache/incubator-tuweni/pull/18#discussion_r287145827
 
 

 ##########
 File path: 
scuttlebutt-handshake/src/main/java/org/apache/tuweni/scuttlebutt/handshake/SecureScuttlebuttStream.java
 ##########
 @@ -139,14 +149,32 @@ private Bytes encrypt(Bytes message, SecretBox.Key 
clientToServerKey, MutableByt
   }
 
   private Bytes encryptMessage(Bytes message, SecretBox.Key key, MutableBytes 
nonce) {
-    SecretBox.Nonce headerNonce = SecretBox.Nonce.fromBytes(nonce);
-    SecretBox.Nonce bodyNonce = SecretBox.Nonce.fromBytes(nonce.increment());
-    nonce.increment();
-    Bytes encryptedBody = SecretBox.encrypt(message, key, bodyNonce);
-    int bodySize = encryptedBody.size() - 16;
-    Bytes encodedBodySize = Bytes.ofUnsignedInt(bodySize).slice(2);
-    Bytes header = SecretBox.encrypt(Bytes.concatenate(encodedBodySize, 
encryptedBody.slice(0, 16)), key, headerNonce);
-
-    return Bytes.concatenate(header, encryptedBody.slice(16));
+    SecretBox.Nonce headerNonce = null;
+    SecretBox.Nonce bodyNonce = null;
+    try {
+      headerNonce = SecretBox.Nonce.fromBytes(nonce);
+      bodyNonce = SecretBox.Nonce.fromBytes(nonce.increment());
+      nonce.increment();
+      Bytes encryptedBody = SecretBox.encrypt(message, key, bodyNonce);
+      int bodySize = encryptedBody.size() - 16;
+      Bytes encodedBodySize = Bytes.ofUnsignedInt(bodySize).slice(2);
+      Bytes header = SecretBox.encrypt(Bytes.concatenate(encodedBodySize, 
encryptedBody.slice(0, 16)), key, headerNonce);
+
+      return Bytes.concatenate(header, encryptedBody.slice(16));
+    } finally {
+      destroyIfNonNull(headerNonce);
+      destroyIfNonNull(bodyNonce);
+    }
+
+  }
+
+  private void destroyIfNonNull(SecretBox.Nonce nonce) {
+    if (nonce != null) {
+      nonce.destroy();
+    }
   }
+
+
+
+
 
 Review comment:
   can you remove the white space please?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to