4 #include "crypto_aes.h"
5 #include "insecure_memzero.h"
8 #include "crypto_aesctr.h"
10 struct crypto_aesctr
{
11 const struct crypto_aes_key
* key
;
18 * crypto_aesctr_init(key, nonce):
19 * Prepare to encrypt/decrypt data with AES in CTR mode, using the provided
20 * expanded key and nonce. The key provided must remain valid for the
21 * lifetime of the stream.
23 struct crypto_aesctr
*
24 crypto_aesctr_init(const struct crypto_aes_key
* key
, uint64_t nonce
)
26 struct crypto_aesctr
* stream
;
28 /* Allocate memory. */
29 if ((stream
= malloc(sizeof(struct crypto_aesctr
))) == NULL
)
32 /* Initialize values. */
34 stream
->nonce
= nonce
;
46 * crypto_aesctr_stream(stream, inbuf, outbuf, buflen):
47 * Generate the next ${buflen} bytes of the AES-CTR stream and xor them with
48 * bytes from ${inbuf}, writing the result into ${outbuf}. If the buffers
49 * ${inbuf} and ${outbuf} overlap, they must be identical.
52 crypto_aesctr_stream(struct crypto_aesctr
* stream
, const uint8_t * inbuf
,
53 uint8_t * outbuf
, size_t buflen
)
59 for (pos
= 0; pos
< buflen
; pos
++) {
60 /* How far through the buffer are we? */
61 bytemod
= stream
->bytectr
% 16;
63 /* Generate a block of cipherstream if needed. */
65 be64enc(pblk
, stream
->nonce
);
66 be64enc(pblk
+ 8, stream
->bytectr
/ 16);
67 crypto_aes_encrypt_block(pblk
, stream
->buf
,
72 outbuf
[pos
] = inbuf
[pos
] ^ stream
->buf
[bytemod
];
74 /* Move to the next byte of cipherstream. */
80 * crypto_aesctr_free(stream):
81 * Free the provided stream object.
84 crypto_aesctr_free(struct crypto_aesctr
* stream
)
87 /* Behave consistently with free(NULL). */
91 /* Zero potentially sensitive information. */
92 insecure_memzero(stream
, sizeof(struct crypto_aesctr
));
94 /* Free the stream. */
99 * crypto_aesctr_buf(key, nonce, inbuf, outbuf, buflen):
100 * Equivalent to _init(key, nonce); _stream(inbuf, outbuf, buflen); _free().
103 crypto_aesctr_buf(const struct crypto_aes_key
* key
, uint64_t nonce
,
104 const uint8_t * inbuf
, uint8_t * outbuf
, size_t buflen
)
106 struct crypto_aesctr stream_rec
;
107 struct crypto_aesctr
* stream
= &stream_rec
;
109 /* Initialize values. */
111 stream
->nonce
= nonce
;
114 /* Perform the encryption. */
115 crypto_aesctr_stream(stream
, inbuf
, outbuf
, buflen
);
117 /* Zero potentially sensitive information. */
118 insecure_memzero(stream
, sizeof(struct crypto_aesctr
));
This page took 0.023913 seconds and 4 git commands to generate.