From f7e4afc2827d285b66fb570f82f411bd6f9b94bb Mon Sep 17 00:00:00 2001 From: orignal Date: Thu, 9 Aug 2018 15:47:02 -0400 Subject: [PATCH] use same buffer for input and output for AEAD/Chacha20/Poly1305 --- libi2pd/Crypto.cpp | 18 ++++++++++++++---- libi2pd/NTCP2.cpp | 6 ++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/libi2pd/Crypto.cpp b/libi2pd/Crypto.cpp index 0a9093a2..3f214b0e 100644 --- a/libi2pd/Crypto.cpp +++ b/libi2pd/Crypto.cpp @@ -1018,9 +1018,6 @@ namespace crypto uint8_t polyKey[64]; memset(polyKey, 0, sizeof(polyKey)); chacha20 (polyKey, 64, nonce, key, 0); - // encrypt data - memcpy (buf, msg, msgLen); - chacha20 (buf, msgLen, nonce, key, 1); // create Poly1305 message if (!ad) adLen = 0; @@ -1038,7 +1035,20 @@ namespace crypto memcpy (polyMsg.data () + offset, padding, rem); offset += rem; } } - memcpy (polyMsg.data () + offset, encrypt ? buf : msg, msgLen); offset += msgLen; // encrypted data + // encrypt/decrypt data and add to hash + memcpy (buf, msg, msgLen); + if (encrypt) + { + chacha20 (buf, msgLen, nonce, key, 1); // encrypt + memcpy (polyMsg.data () + offset, buf, msgLen); // after encryption + } + else + { + memcpy (polyMsg.data () + offset, buf, msgLen); // before decryption + chacha20 (buf, msgLen, nonce, key, 1); // decrypt + } + offset += msgLen; // encrypted data + auto rem = msgLen & 0x0F; // %16 if (rem) { diff --git a/libi2pd/NTCP2.cpp b/libi2pd/NTCP2.cpp index 6f524920..91b897f5 100644 --- a/libi2pd/NTCP2.cpp +++ b/libi2pd/NTCP2.cpp @@ -697,11 +697,10 @@ namespace transport i2p::transport::transports.UpdateReceivedBytes (bytes_transferred); uint8_t nonce[12]; CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++; - uint8_t * decrypted = new uint8_t[m_NextReceivedLen]; - if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, decrypted, m_NextReceivedLen, false)) + if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false)) { LogPrint (eLogDebug, "NTCP2: received message decrypted"); - ProcessNextFrame (decrypted, m_NextReceivedLen-16); + ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16); delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore ReceiveLength (); } @@ -710,7 +709,6 @@ namespace transport LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed "); SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure); } - delete[] decrypted; } }