00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include <core/exceptions/software.h>
00025 #include <netcomm/worldinfo/decrypt.h>
00026 #ifdef HAVE_LIBCRYPTO
00027 # include <openssl/evp.h>
00028 #else
00029 # include <cstring>
00030 #endif
00031
00032 namespace fawkes {
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044 MessageDecryptionException::MessageDecryptionException(const char *msg)
00045 : Exception(msg)
00046 {
00047 }
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071 WorldInfoMessageDecryptor::WorldInfoMessageDecryptor(const unsigned char *key, const unsigned char *iv)
00072 {
00073 plain_buffer = NULL;
00074 plain_buffer_length = 0;
00075 crypt_buffer = NULL;
00076 crypt_buffer_length = 0;
00077
00078 this->key = key;
00079 this->iv = iv;
00080 }
00081
00082
00083
00084 WorldInfoMessageDecryptor::~WorldInfoMessageDecryptor()
00085 {
00086 }
00087
00088
00089
00090
00091
00092
00093
00094 void
00095 WorldInfoMessageDecryptor::set_plain_buffer(void *buffer, size_t buffer_length)
00096 {
00097 plain_buffer = buffer;
00098 plain_buffer_length = buffer_length;
00099 }
00100
00101
00102
00103
00104
00105
00106
00107 void
00108 WorldInfoMessageDecryptor::set_crypt_buffer(void *buffer, size_t buffer_length)
00109 {
00110 crypt_buffer = buffer;
00111 crypt_buffer_length = buffer_length;
00112 }
00113
00114
00115
00116
00117
00118
00119 size_t
00120 WorldInfoMessageDecryptor::decrypt()
00121 {
00122 if ( (plain_buffer == NULL) || (plain_buffer_length == 0) ||
00123 (crypt_buffer == NULL) || (crypt_buffer_length == 0) ) {
00124 throw MissingParameterException("Buffer(s) not set for decryption");
00125 }
00126
00127 #ifdef HAVE_LIBCRYPTO
00128 EVP_CIPHER_CTX ctx;
00129 if ( ! EVP_DecryptInit(&ctx, EVP_aes_128_ecb(), key, iv) ) {
00130 throw MessageDecryptionException("Could not initialize cipher context");
00131 }
00132
00133 int outl = plain_buffer_length;
00134 if ( ! EVP_DecryptUpdate(&ctx,
00135 (unsigned char *)plain_buffer, &outl,
00136 (unsigned char *)crypt_buffer, crypt_buffer_length) ) {
00137 throw MessageDecryptionException("DecryptUpdate failed");
00138 }
00139
00140 int plen = 0;
00141 if ( ! EVP_DecryptFinal(&ctx, (unsigned char *)plain_buffer + outl, &plen) ) {
00142 throw MessageDecryptionException("DecryptFinal failed");
00143 }
00144 outl += plen;
00145
00146 return outl;
00147 #else
00148
00149 memcpy(plain_buffer, crypt_buffer, crypt_buffer_length);
00150 return crypt_buffer_length;
00151 #endif
00152 }
00153
00154 }