From e378d2e30a40bd9bcee06dc3a4250f269098e200 Mon Sep 17 00:00:00 2001 From: Thomas Date: Fri, 10 Feb 2017 20:39:01 +0100 Subject: [PATCH] openssl: move shared AES-CTR code into misc --- src/misc.c | 28 ++++++++++++++++++++++++++++ src/misc.h | 7 +++++++ src/openssl.c | 12 +++--------- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/misc.c b/src/misc.c index f7faae7b..94904ab5 100644 --- a/src/misc.c +++ b/src/misc.c @@ -643,3 +643,31 @@ void *_libssh2_calloc(LIBSSH2_SESSION* session, size_t size) } return p; } + +/* XOR operation on buffers input1 and input2, result in output. + It is safe to use an input buffer as the output buffer. */ +void _libssh2_xor_data(unsigned char *output, + const unsigned char *input1, + const unsigned char *input2, + size_t length) +{ + size_t i; + + for (i = 0; i < length; i++) + *output++ = *input1++ ^ *input2++; +} + +/* Increments an AES CTR buffer to prepare it for use with the + next AES block. */ +void _libssh2_aes_ctr_increment(unsigned char *ctr, + size_t length) +{ + if (length == 0) + return; + size_t i = (length - 1); + while (ctr[i]++ == 0xFF) { + if (i == 0) + break; + i--; + } +} diff --git a/src/misc.h b/src/misc.h index 54ae5461..44e2996d 100644 --- a/src/misc.h +++ b/src/misc.h @@ -93,4 +93,11 @@ int __cdecl _libssh2_gettimeofday(struct timeval *tp, void *tzp); #endif #endif +void _libssh2_xor_data(unsigned char *output, + const unsigned char *input1, + const unsigned char *input2, + size_t length); + +void _libssh2_aes_ctr_increment(unsigned char *ctr, size_t length); + #endif /* _LIBSSH2_MISC_H */ diff --git a/src/openssl.c b/src/openssl.c index b7b146cd..f10f2921 100644 --- a/src/openssl.c +++ b/src/openssl.c @@ -43,6 +43,7 @@ #ifdef LIBSSH2_OPENSSL /* compile only if we build with openssl */ #include +#include "misc.h" #ifndef EVP_MAX_BLOCK_LENGTH #define EVP_MAX_BLOCK_LENGTH 32 @@ -364,15 +365,8 @@ aes_ctr_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, return 0; } - for (i = 0; i < 16; i++) - *out++ = *in++ ^ b1[i]; - - i = 15; - while (c->ctr[i]++ == 0xFF) { - if (i == 0) - break; - i--; - } + _libssh2_xor_data(out, in, b1, AES_BLOCK_SIZE); + _libssh2_aes_ctr_increment(c->ctr, AES_BLOCK_SIZE); return 1; }