4 * Copyright (c) Freescale Semiconductor, Inc. All rights reserved.
5 * See included license file for license details.
10 #include "smart_ptr.h"
11 #include "HexValues.h"
14 //! The data from the stream is expected to be hex encoded. Each two characters
15 //! from the stream encode a single result byte. All non-hexadecimal characters
16 //! are ignored, including newlines. Every two hexadecimal characters form
17 //! an encoded byte. This is true even if the two characters representing the
18 //! upper and lower nibbles are separated by whitespace or other characters.
20 //! \post The stream read head is left pointing just after the last encoded byte.
22 //! \param stream Input stream to read from.
23 //! \param bytes Number of encoded bytes to read. This is the number of \e
24 //! result bytes, not the count of bytes to read from the stream.
25 //! \param[out] buffer Pointer to the buffer where decoded data is written.
27 //! \exception std::runtime_error This exception will be thrown if less
28 //! data than required is available from \a stream, or if some other
29 //! error occurs while reading from \a stream.
30 void AESKeyBase::_readFromStream(std::istream & stream, unsigned bytes, uint8_t * buffer)
38 if (stream.get(c).fail())
40 throw std::runtime_error("not enough data in stream");
48 *buffer++ = hexByteToInt(temp);
56 //! Key data is written to \a stream as a sequence of hex encoded octets, each two
57 //! characters long. No spaces or newlines are inserted between the encoded octets
58 //! or at the end of the sequence.
60 //! \exception std::runtime_error Thrown if the \a stream reports an error while
61 //! writing the key data.
62 void AESKeyBase::_writeToStream(std::ostream & stream, unsigned bytes, const uint8_t * buffer)
64 const char hexChars[] = "0123456789ABCDEF";
67 uint8_t thisByte = *buffer++;
69 byteString[0] = hexChars[(thisByte & 0xf0) >> 4];
70 byteString[1] = hexChars[thisByte & 0x0f];
71 if (stream.write(byteString, 2).bad())
73 throw std::runtime_error("error while writing to stream");