| 68 | } |
| 69 | |
| 70 | void CodedInputDataCrypt::consumeBytes(size_t length, bool discardPreData) { |
| 71 | if (discardPreData) { |
| 72 | m_decryptBufferDiscardPosition = m_decryptBufferPosition; |
| 73 | } |
| 74 | auto decryptedBytesLeft = m_decryptBufferDecryptLength - m_decryptBufferPosition; |
| 75 | if (decryptedBytesLeft >= length) { |
| 76 | return; |
| 77 | } |
| 78 | length -= decryptedBytesLeft; |
| 79 | |
| 80 | // if there's some data left inside m_decrypter.m_vector, use them first |
| 81 | // it will be faster when always decrypt with (n * AES_IV_LEN) bytes |
| 82 | if (m_decrypter.m_number != 0) { |
| 83 | auto alignDecrypter = AES_IV_LEN - m_decrypter.m_number; |
| 84 | // make sure no data left inside m_decrypter.m_vector after decrypt |
| 85 | if (length < alignDecrypter) { |
| 86 | length = alignDecrypter; |
| 87 | } else { |
| 88 | length -= alignDecrypter; |
| 89 | length = ((length + AES_IV_LEN - 1) / AES_IV_LEN) * AES_IV_LEN; |
| 90 | length += alignDecrypter; |
| 91 | } |
| 92 | } else { |
| 93 | length = ((length + AES_IV_LEN - 1) / AES_IV_LEN) * AES_IV_LEN; |
| 94 | } |
| 95 | auto bytesLeftInSrc = m_size - m_decryptPosition; |
| 96 | length = min(bytesLeftInSrc, length); |
| 97 | |
| 98 | auto bytesLeftInBuffer = m_decryptBufferSize - m_decryptBufferDecryptLength; |
| 99 | // try move some space |
| 100 | if (bytesLeftInBuffer < length && m_decryptBufferDiscardPosition > 0) { |
| 101 | auto posToMove = (m_decryptBufferDiscardPosition / AES_IV_LEN) * AES_IV_LEN; |
| 102 | if (posToMove) { |
| 103 | auto sizeToMove = m_decryptBufferDecryptLength - posToMove; |
| 104 | memmove(m_decryptBuffer, m_decryptBuffer + posToMove, sizeToMove); |
| 105 | m_decryptBufferPosition -= posToMove; |
| 106 | m_decryptBufferDecryptLength -= posToMove; |
| 107 | m_decryptBufferDiscardPosition = 0; |
| 108 | bytesLeftInBuffer = m_decryptBufferSize - m_decryptBufferDecryptLength; |
| 109 | } |
| 110 | } |
| 111 | // still no enough space, try realloc() |
| 112 | if (bytesLeftInBuffer < length) { |
| 113 | auto newSize = m_decryptBufferSize + length; |
| 114 | auto newBuffer = realloc(m_decryptBuffer, newSize); |
| 115 | if (!newBuffer) { |
| 116 | throw runtime_error(strerror(errno)); |
| 117 | } |
| 118 | m_decryptBuffer = (uint8_t *) newBuffer; |
| 119 | m_decryptBufferSize = newSize; |
| 120 | } |
| 121 | m_decrypter.decrypt(m_ptr + m_decryptPosition, m_decryptBuffer + m_decryptBufferDecryptLength, length); |
| 122 | m_decryptPosition += length; |
| 123 | m_decryptBufferDecryptLength += length; |
| 124 | assert(m_decryptPosition == m_size || m_decrypter.m_number == 0); |
| 125 | } |
| 126 | |
| 127 | void CodedInputDataCrypt::skipBytes(size_t length) { |