-rw-r--r-- 2601 cryptattacktester-20230614/aes128.cpp raw
#include <cassert>
#ifdef OPENSSL_OLD_API
#include <openssl/aes.h>
#else
#include <openssl/evp.h>
#endif
#include "bigint.h"
#include "random.h"
#include "selection.h"
#include "aes128.h"
using namespace std;
static void aes128_bytes(unsigned char *out,const unsigned char *in,const unsigned char *key)
{
#ifdef OPENSSL_OLD_API
AES_KEY expandedkey;
AES_set_encrypt_key(key,128,&expandedkey);
AES_encrypt(in,out,&expandedkey);
#else
EVP_CIPHER_CTX *e;
e = EVP_CIPHER_CTX_new();
assert(e);
assert(EVP_EncryptInit_ex(e,EVP_aes_128_ecb(),0,key,in) == 1);
int outl = 0;
assert(EVP_EncryptUpdate(e,out,&outl,in,16) == 1);
assert(outl == 16);
EVP_CIPHER_CTX_free(e);
#endif
}
vector<vector<bigint>> aes128_params(map<string,string> &S)
{
vector<vector<bigint>> result;
bigint Kmin = 1;
bigint Kmax = 128;
selection_constrain(S,"K",Kmin,Kmax);
for (bigint K = Kmin;K <= Kmax;++K) {
if (K < 1) continue;
if (K > 128) continue;
bigint Cmin = 1;
bigint Cmax = 128;
selection_constrain(S,"C",Cmin,Cmax);
for (bigint C = Cmin;C <= Cmax;++C) {
if (C < 1) continue;
if (C > 128) continue;
result.push_back(vector<bigint> {K,C});
}
}
return result;
}
bigint aes128_numinputs(const vector<bigint> ¶ms)
{
bigint K = params.at(0);
return bigint(1) << K;
}
bigint aes128_numoutputs(const vector<bigint> ¶ms)
{
bigint C = params.at(1);
return bigint(1) << (2*C);
}
pair<vector<bool>,vector<bool>> aes128(const vector<bigint> ¶ms)
{
bigint K = params.at(0);
bigint C = params.at(1);
vector<bool> keybits;
for (bigint j = 0;j < K;++j)
keybits.push_back(random_bool());
unsigned char keybytes[16];
for (bigint j = 0;j < 16;++j)
keybytes[j] = 0;
for (bigint j = 0;j < 128 && j < K;++j)
keybytes[j/8] += (int(keybits.at(j))<<int(j%8));
vector<bool> publicbits;
for (bigint blocknum = 0;blocknum < 2;++blocknum) {
vector<bool> plaintextbits;
for (bigint j = 0;j < 128;++j)
plaintextbits.push_back(random_bool());
unsigned char plaintextbytes[16];
for (bigint j = 0;j < 16;++j)
plaintextbytes[j] = 0;
for (bigint j = 0;j < 128;++j)
plaintextbytes[j/8] += (int(plaintextbits.at(j))<<int(j%8));
for (bigint j = 0;j < 128;++j)
publicbits.push_back(1&(plaintextbytes[j/8]>>int(j%8)));
unsigned char ciphertextbytes[16];
aes128_bytes(ciphertextbytes,plaintextbytes,keybytes);
for (bigint j = 0;j < 128 && j < C;++j)
publicbits.push_back(1&(ciphertextbytes[j/8]>>int(j%8)));
}
return make_pair(publicbits,keybits);
}