Browse Source

use same buffer for input and output for AEAD/Chacha20/Poly1305

pull/1221/head
orignal 6 years ago
parent
commit
f7e4afc282
  1. 18
      libi2pd/Crypto.cpp
  2. 6
      libi2pd/NTCP2.cpp

18
libi2pd/Crypto.cpp

@ -1018,9 +1018,6 @@ namespace crypto
uint8_t polyKey[64]; uint8_t polyKey[64];
memset(polyKey, 0, sizeof(polyKey)); memset(polyKey, 0, sizeof(polyKey));
chacha20 (polyKey, 64, nonce, key, 0); chacha20 (polyKey, 64, nonce, key, 0);
// encrypt data
memcpy (buf, msg, msgLen);
chacha20 (buf, msgLen, nonce, key, 1);
// create Poly1305 message // create Poly1305 message
if (!ad) adLen = 0; if (!ad) adLen = 0;
@ -1038,7 +1035,20 @@ namespace crypto
memcpy (polyMsg.data () + offset, padding, rem); offset += rem; 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 auto rem = msgLen & 0x0F; // %16
if (rem) if (rem)
{ {

6
libi2pd/NTCP2.cpp

@ -697,11 +697,10 @@ namespace transport
i2p::transport::transports.UpdateReceivedBytes (bytes_transferred); i2p::transport::transports.UpdateReceivedBytes (bytes_transferred);
uint8_t nonce[12]; uint8_t nonce[12];
CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++; 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, m_NextReceivedBuffer, m_NextReceivedLen, false))
if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, decrypted, m_NextReceivedLen, false))
{ {
LogPrint (eLogDebug, "NTCP2: received message decrypted"); 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 delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore
ReceiveLength (); ReceiveLength ();
} }
@ -710,7 +709,6 @@ namespace transport
LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed "); LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed ");
SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure); SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure);
} }
delete[] decrypted;
} }
} }

Loading…
Cancel
Save