Пример #1
1
int RunAESDemo()
{
	AES aes;

	vector<unsigned char> key;
	aes.GenerateKey( 256, key );

	printf( "key.size(): %d\n", (int)key.size() );

//	unsigned char buffer[50000]; // 50KB
	size_t read_bytes = 0;

	vector<unsigned char> plaintext;
	plaintext.resize(50000,0);

//	string plaintext_file = "input_data/plaintext/plaintext_example.txt";
//	string plaintext_file = "input_data/plaintext/0s.txt";
	string plaintext_file = "input_data/plaintext/more0s.txt";
	FILE *fp = fopen( plaintext_file.c_str(), "rb" );
	if(fp)
	{
//		read_bytes = fread(buffer,sizeof(buffer),1,fp);
		read_bytes = fread(&plaintext[0], sizeof(unsigned char), plaintext.size(), fp);
		printf( "read_bytes: %d\n", (int)read_bytes );
		fclose(fp);
	}

	vector<unsigned char> ciphertext;
	aes.Encrypt( plaintext, ciphertext );

	printf( "ciphertext.size(): %d\n", (int)ciphertext.size() );

	if( 0 < ciphertext.size() )
	{
		fp = fopen( string(plaintext_file + ".encrypted").c_str(), "wb" );
		if(fp)
		{
			size_t written_bytes = fwrite(&ciphertext[0], sizeof(unsigned char), ciphertext.size(), fp);
			printf( "written_bytes: %d\n", (int)written_bytes );
			fclose(fp);
		}
	}

	return 0;
}
Пример #2
0
Mikey_Payloads* Mikey_Payload_KEMAC::decode_payloads( int firstPayloadType, byte_t * encrKey, int encrKeyLength, byte_t * iv )
{
    byte_t * decrData = new byte_t[ encr_data_length_value ];
    AES * aes;

    switch( encr_alg_value)
    {
    case MIKEY_PAYLOAD_KEMAC_ENCR_AES_CM_128:
        aes = new AES( encrKey, encrKeyLength );
        aes->ctr_encrypt( encr_data_ptr, encr_data_length_value, decrData, iv );
        delete aes;
        break;
    case MIKEY_PAYLOAD_KEMAC_ENCR_NULL:
        memcpy( decrData, encr_data_ptr, encr_data_length_value );
        break;
    case MIKEY_PAYLOAD_KEMAC_ENCR_AES_KW_128:
        //TODO
    default:
        delete [] decrData;
        throw Mikey_Exception(
                    "Unknown encryption algorithm" );
        break;
    }

    Mikey_Payloads *output =
            new Mikey_Payloads( firstPayloadType, decrData, encr_data_length_value );
    // decrData is owned and deleted by MikeyPayloads
    return output;
}
Пример #3
0
int main(char* args[]) {

	// instantiate classes
	InOut* io = new InOut();
	AES* aes;
	
	// delete output files
	if (OUTPUTKEYEXP) { remove(FOUT_KEYEXP); }
	if (OUTPUTENCRYPT) { remove(FOUT_ENCRYPT); }
	if (OUTPUTDECRYPT) { remove(FOUT_DECRYPT); }

	// run for all three key sizes
	for(int keySize = 128; keySize <= 256; keySize = keySize + 64) {

		// title
		cout<<"AES (Rijndael) - w/ "<<dec<<keySize<<" Bit Key";
		
		// get key and create cryptographic class
		byte* key = io->getKey(keySize);
		aes = new AES(keySize, key);

		// get message
		byte* plaintext = io->get16BytesOfMessage();

		// print original message
		cout<<"\n\nOriginal Message:\n";
		for(int i=0; i<16; i++) {
			cout<<hex<<setfill('0')<<setw(2);
			cout<<int(plaintext[i]);
		}	

		// run encryption
		byte* ciphertext = new byte[16];
		ciphertext = aes->encrypt(plaintext);

		// print ciphertext
		cout<<"\n\nEncrypted Message:\n";
		for(int i=0; i<16; i++) {
			cout<<hex<<setfill('0')<<setw(2);
			cout<<int(ciphertext[i]);
		}

		// run decryption
		byte* decrypttext = aes->decrypt(ciphertext);

		// recovered plaintext
		cout<<"\n\nDecrypted Message:\n";
		for(int i=0; i<16; i++) {
			cout<<hex<<setfill('0')<<setw(2);
			cout<<int(decrypttext[i]);
		}

		cout<<"\n\n";

	}

	return 0;

}
uint8_t transportReceive(void* data) {
	uint8_t len = _rf24.getDynamicPayloadSize();
	_rf24.read(data, len);
	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		_aes.set_IV(0);//not sure if necessary
		_aes.cbc_decrypt((byte*)(data), (byte*)(data), len>16?2:1); // decrypt
	#endif
	return len;
}
uint8_t transportReceive(void* data) {
	uint8_t len = RF24_readMessage(data);
	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		// has to be adjusted, WIP!
		_aes.set_IV(0);
		// decrypt data
		_aes.cbc_decrypt((byte*)(data), (byte*)(data), len>16?2:1);
	#endif
	return len;
}
Пример #6
0
void GenWzKey(const uint8_t* IV, uint8_t* key) {
	uint8_t BigIV[16];
	for (int i = 0; i < 16; i += 4) {
		memcpy(BigIV+i, IV, 4);
	}
	AESGen.SetParameters(256, 128);
	AESGen.StartEncryption(AESKey2);
	AESGen.EncryptBlock(BigIV, key);
	for (int i = 16; i < 0x10000; i += 16) {
		AESGen.EncryptBlock(key+i-16, key+i);
	}
}
Пример #7
0
/**
 * Encrypts the actual text using the password
 * @param password Password
 * @return Encrypted text
 */
QByteArray MainWindow::encrypt(QString password)
{
    AES crypto;

    QString hashedPassword = QString( QCryptographicHash::hash(( password.toUtf8() ),QCryptographicHash::Md5).toHex() );

    QByteArray key = crypto.hexStringToByte(hashedPassword);
    QByteArray data = ui->textEdit_mainWindow_surface->toHtml().toUtf8();

    QByteArray encrypted = crypto.encrypt(data, key);

    return encrypted;
}
Пример #8
0
/**
 * Decrypts the actual text using the password
 * @param password Password
 * @return Decrypted text
 */
QByteArray MainWindow::decrypt(QString password)
{
    AES crypto;

    QString hashedPassword = QString( QCryptographicHash::hash(( password.toUtf8() ),QCryptographicHash::Md5).toHex() );

    QByteArray key = crypto.hexStringToByte(hashedPassword);
    QByteArray data = QByteArray::fromBase64( ui->textEdit_mainWindow_surface->toPlainText().toUtf8() );

    QByteArray decrypted = crypto.decrypt(data, key);

    return decrypted;
}
bool transportInit() {

	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		hwReadConfigBlock((void*)_psk, (void*)EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS, 32);
		//set up AES-key
		_aes.set_key(_psk, 32);
		// Make sure it is purged from memory when set
		memset(_psk, 0, 32);
		//set up AES IV
		hwReadConfigBlock((void*)IVCl,(void*)EEPROM_RF_ENCRYPTION_AES_IV_ADDRESS,8);
		_aes.set_IV(IVCl);
	#endif

	return RF24_initialize();
}
Пример #10
0
bool transportSend(const uint8_t to, const void *data, const uint8_t len, const bool noACK)
{
#if defined(MY_RF24_ENABLE_ENCRYPTION)
	// copy input data because it is read-only
	(void)memcpy(RF24_dataenc,data,len);
	// has to be adjusted, WIP!
	RF24_aes.set_IV(0);
	const uint8_t finalLength = len > 16 ? 32 : 16;
	//encrypt data
	RF24_aes.cbc_encrypt(RF24_dataenc, RF24_dataenc, finalLength / 16);
	return RF24_sendMessage(to, RF24_dataenc, finalLength, noACK);
#else
	return RF24_sendMessage(to, data, len, noACK);
#endif
}
bool transportInit() {
	// Start up the radio library
	_rf24.begin();

	if (!_rf24.isPVariant()) {
		return false;
	}
	_rf24.setAutoAck(1);
	_rf24.setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast
	_rf24.enableAckPayload();
	_rf24.setChannel(MY_RF24_CHANNEL);
	_rf24.setPALevel(_paLevel);
	if (!_rf24.setDataRate(MY_RF24_DATARATE)) {
		return false;
	}
	_rf24.setRetries(5,15);
	_rf24.setCRCLength(RF24_CRC_16);
	_rf24.enableDynamicPayloads();

	// All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages)
	_rf24.openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS));


	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		_aes.set_key(_psk, 16); //set up AES-key
	#endif

	//_rf24.printDetails();

	return true;
}
Пример #12
0
int main(int argc, char **argv) {
	if(argc < 2) {
		printf("USAGE: benchmark FILE\n");
		return 1;
	}

	byte key[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
	uint keySize = 16;

	uint *ct, *pt;
	
	FILE *f = fopen(argv[1], "rb");
	if(f == NULL) {
		printf("File not found.\n");
		return 1;
	}

	fseek(f, 0, SEEK_END);
	uint f_size = ftell(f);
	rewind(f);

	if(f_size % 4*sizeof(uint) != 0) {
		printf("Plaintext size must be a multiple of AES block size.\n");
		return 1;
	}

	uint ptSize = f_size / sizeof(uint);
	
	pt = (uint*)malloc(f_size);
	fread(pt, sizeof(uint), ptSize, f);
	fclose(f);

	ct = (uint *)malloc(ptSize*sizeof(uint));

	AES *aes = new AES();
	aes->makeKey(key, keySize << 3, DIR_ENCRYPT);

	clock_t start = clock();
	for(uint i = 0; i < ptSize; i += 4) {
		aes->encrypt(pt + i, ct + i);
	}
	clock_t end = clock();

	printf("%d blocks encrypted in %d/%d seconds.\n", ptSize >> 2, end-start, CLOCKS_PER_SEC);

	return 0;
}
void CDialogOption::OnOK() {
    USES_CONVERSION;

    if (!UpdateData(TRUE)) {
        return;
    }

    AES aes;
    CString ak;
    CString sk;

    if (m_strAK.Trim().IsEmpty()) {
        MessageBox(_T("ÇëÊäÈë'AK'¡£"));
        return;
    }

    if (m_strSK.Trim().IsEmpty()) {
        MessageBox(_T("ÇëÊäÈë'SK'¡£"));
        return;
    }

    if (m_strHost.Trim().IsEmpty())  {
        MessageBox(_T("ÇëÊäÈë'·þÎñÆ÷µØÖ·'¡£"));
        return;
    }

    lc_bce_access_key_t key = { 0 };
    strncpy_s(key.access_key_id, T2A(m_strAK), -1);
    strncpy_s(key.secret_access_key, T2A(m_strSK), -1);

    if (m_pParent->DoAuth(&key, m_strHost, FALSE)) {

        aes.Encrypt(m_strAK, ak);
        aes.Encrypt(m_strSK, sk);

        ConfigMgr::Instance().SetAk(ak);
        ConfigMgr::Instance().SetSk(sk);
        ConfigMgr::Instance().SetHost(m_strHost);
        m_pParent->UpdateLiveCaptureData();

        EndDialog(IDOK);
        DestroyWindow();
    }
}
BOOL CDialogOption::OnInitDialog() {
    CString ak;
    CString sk;
    CString host;
    ConfigMgr::Instance().GetAk(ak);
    ConfigMgr::Instance().GetSk(sk);
    ConfigMgr::Instance().GetHost(host);

    AES aes;

    aes.Decrypt(ak, ak);
    aes.Decrypt(sk, sk);

    m_strAK = m_strAKbak = ak;
    m_strSK = m_strSKbak = sk;
    m_strHost = m_strHostbak = host;

    CDialog::OnInitDialog();
    return TRUE;
}
Пример #15
0
bool transportSend(uint8_t recipient, const void* data, uint8_t len) {
	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		// copy input data because it is read-only
		memcpy(_dataenc,data,len);
		len = len > 16 ? 32 : 16;
		#if defined(MY_GATEWAY_FEATURE)
			SdReadNodeData(RF24_getNodeID(), nd);
			_aes.set_key(nd.AES_256,32);
			_aes.set_IV(nd.IV);
		#else
		#endif
		//encrypt data
		_aes.set_IV(IVCl);
		_aes.cbc_encrypt(_dataenc, _dataenc, len/16);
		bool status = RF24_sendMessage( recipient, _dataenc, len );
	#else
		bool status = RF24_sendMessage( recipient, data, len );
	#endif

	return status;
}
bool transportSend(uint8_t to, const void* data, uint8_t len) {
	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		memcpy(_dataenc,data,len); // copy input data because it is read-only

		_aes.set_IV(0);//not sure if necessary
		len = len > 16 ? 32 : 16;
		_aes.cbc_encrypt(_dataenc, _dataenc, len/16); //encrypt
	#endif

	// Make sure radio has powered up

	_rf24.powerUp();
	_rf24.stopListening();
	_rf24.openWritingPipe(TO_ADDR(to));
	#if defined(MY_RF24_ENABLE_ENCRYPTION)
		bool ok = _rf24.write(_dataenc, len, to == BROADCAST_ADDRESS);
	#else
		bool ok = _rf24.write(data, len, to == BROADCAST_ADDRESS);
	#endif
	_rf24.startListening();
	return ok;
}
Пример #17
0
uint8_t transportReceive(void *data)
{
	uint8_t len = 0;
#if defined(MY_RX_MESSAGE_BUFFER_FEATURE)
	transportQueuedMessage* msg = transportRxQueue.getBack();
	if (msg) {
		len = msg->m_len;
		(void)memcpy(data, msg->m_data, len);
		(void)transportRxQueue.popBack();
	}
#else
	len = RF24_readMessage(data);
#endif
#if defined(MY_RF24_ENABLE_ENCRYPTION)
	// has to be adjusted, WIP!
	RF24_aes.set_IV(0);
	// decrypt data
	if (RF24_aes.cbc_decrypt((uint8_t *)data, (uint8_t *)data, len > 16 ? 2 : 1) != AES_SUCCESS) {
		len = 0;
	}
#endif
	return len;
}
Пример #18
0
void Crypto::TransformData(uint8_t* IV, uint8_t* data, uint32_t len) {
	uint8_t BigIV[16];
	for (int i = 0; i < 16; i += 4) {
		memcpy(BigIV+i, IV, 4);
	}

	uint32_t pos = 0;
	uint8_t first = 1;
	int32_t tpos = 0;
	while (len > pos) {
		AESGen.SetParameters(256, 128);
		AESGen.StartEncryption(AESKey2);
		tpos = 1460 - first * 4;
		if (len > pos + tpos) {
			AESGen.TransformOFB(data + pos, BigIV, tpos);
		}
		else {
			AESGen.TransformOFB(data + pos, BigIV, len - pos);
		}
		pos += tpos;
		if (first) first = 0;
	}
}
Пример #19
0
bool transportInit(void)
{
#if defined(MY_RF24_ENABLE_ENCRYPTION)
	uint8_t RF24_psk[16];
#ifdef MY_ENCRYPTION_SIMPLE_PASSWD
	(void)memset(RF24_psk, 0, 16);
	(void)memcpy(RF24_psk, MY_ENCRYPTION_SIMPLE_PASSWD, strnlen(MY_ENCRYPTION_SIMPLE_PASSWD, 16));
#else
	hwReadConfigBlock((void *)RF24_psk, (void *)EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS, 16);
#endif
	//set up AES-key
	RF24_aes.set_key(RF24_psk, 16);
	// Make sure it is purged from memory when set
	(void)memset(RF24_psk, 0, 16);
#endif

#if defined(MY_RX_MESSAGE_BUFFER_FEATURE)
	RF24_registerReceiveCallback( transportRxCallback );
#endif
	return RF24_initialize();
}
Пример #20
0
unsigned int AES_get_encrypted_array_size(unsigned int user_array_size)
{
	return Crypt.get_encrypted_array_size(user_array_size);
}
Пример #21
0
void AES_decryption(char *key, char * encrypted_array, char* decrypted_array, unsigned int encrypted_array_size, unsigned int* data_size)
{
	Crypt.decryption(key, encrypted_array, decrypted_array, encrypted_array_size, data_size);
}		
Пример #22
0
void AES_encryption(char* chain, char *key, char * user_array, char* encrypted_array, unsigned int user_array_size)
{
	Crypt.encryption(chain, key, user_array, encrypted_array, user_array_size);
}	
Пример #23
0
int _tmain(int argc, _TCHAR* argv[])
{
	AES* AESCipher = NULL;
	string msg;
	string key;
	char* temp_msg_hex;
	char* temp_key_hex;
	int mode = -1;

	while (mode != 0 && mode != 1) {
		cout << "Please choose the AES mode (0 for CBC, 1 for CTR): ";

		cin >> mode;
		
		switch (mode) {
		case 0:
			AESCipher = new AES128CBC();
			break;
		case 1:
			AESCipher = new AES128CTR();
			break;
		}

		cin.clear();
		cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
	}

	if (NULL == AESCipher) {
		cout << "Error allocating memory for cipher engine, program exiting...\n";
		return 0;
	}

	cout << "please provide the key: ";
	cin >> key;

	cout << "please provide the message text: ";
	cin >> msg;
	
	temp_key_hex = new char[key.length() + 1];
	for (int i = 0; i < key.length(); i++) {
		temp_key_hex[i] = key.c_str()[i];
	}
	temp_key_hex[key.length()] = 0;

	temp_msg_hex = new char[msg.length() + 1];
	for (int i = 0; i < msg.length(); i++) {
		temp_msg_hex[i] = msg.c_str()[i];
	}
	temp_msg_hex[msg.length()] = 0;

	AESCipher->setKey(temp_key_hex);

	mode = -1;
	while (/* mode != 0 && */ mode != 1) {
		cout << "Please choose whether you want to encrypt or decrypt (1 for decrypt, encrypt is not ready): ";
		cin >> mode;

		switch (mode) {
		case 0:
			AESCipher->setPT(temp_msg_hex);
			AESCipher->Encrypt();
			break;
		case 1:
			AESCipher->setCT(temp_msg_hex);
			AESCipher->Decrypt();
			break;
		}

		cin.clear();
		cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
	}


	return 0;
}
Пример #24
0
/**
testing.
*/
int mainCryptopp(const char* encryptPath, const char* decryptPath)
{
    printf("/***************************************************************************\n");
    printf("C++ crypto, wrap cryptopp interface, reference to www.cryptopp.com\n");
    printf("[email protected] 2006-5-25\n");
    printf("***************************************************************************/\n");

    // base64 testing.
    {
        printf("\n=======================base64=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base64::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base64::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base64 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base64::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base64::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // base16 testing.
    {
        printf("\n=======================base16=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base16::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base16::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base16 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base16::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base16::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // RSA testing.
    {
        printf("\n=======================RSA PKCS #1=====================\n");
        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // init RSA public key encryptor.
        RSA enc;
        enc.initPublicKey(N, e);

        // encrypt.
        int maxoutlen = enc.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = enc.encrypt(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // init private for RSA decryptor.
        RSA dec;
        dec.initPrivateKey(N, e, d);

        // decrypt.
        int maxinlen = dec.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = dec.decrypt(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] orgdata;
    }

    // AES/CBC/PKCS5Padding testing.
    {
        printf("\n=======================AES/CBC/PKCS5Padding=====================\n");
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";

        // init AES.
        AES aes;
        aes.init(key, 16, iv);

        // input data.
        // const char * indata = "bsmith is a good guy.";
        // const char * indata = "bsmith.";
        const char * indata = "I am a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // encrypt.
        int maxoutlen = aes.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = 0;
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }

        // decrypt.
        int maxinlen = aes.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        {
            
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }
        {
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }

        delete[] outdata;
        delete[] orgdata;

    }

    // SHA1 testing.
    {
        printf("\n=======================SHA1=====================\n");

        SHA1 sha1;

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }
    }

    // RSA-SHA1 Sign testing.
    {
        printf("\n=======================RSA-SHA1 Sign=====================\n");

        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        Sign sign;
        // private key for signer.
        sign.initPrivateKey(N, e, d);

        // sign.
        int maxoutlen = sign.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = sign.sign(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // public key for verifier.
        sign.initPublicKey(N, e);

        // verify.
        {
            bool res = sign.verify(indata, inlen, outdata, outlen);
            printf("result <?> true : %s\n", res?"true":"false");
        }
        
        // another data.
        const char * indata1 = "bsmith is not a good guy.";
        int inlen1 = (int)strlen(indata1);
        {
            bool res = sign.verify(indata1, inlen1, outdata, outlen);
            printf("result <?> false : %s\n", res?"true":"false");
        }

        delete[] outdata;
    }

    //printf("press any key to exit!");
    //getchar();
    
    {
        //my test
        unsigned long decryptSize = 0;
        char* decryptBuffer = (char*)getFileData(decryptPath, &decryptSize);
        
        unsigned long encryptSize = 0;
        char* encryptBuffer = (char*)getFileData(encryptPath, &encryptSize);
        
        printf("decryptBuffer(hex)=");
        dump(decryptBuffer, decryptSize);
        
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";
        
        // init AES.
        AES aes;
        aes.init(key, 16, iv);
        {
            // decrypt.
            int maxinlen = aes.getPlainLen(encryptSize);
            char * orgdata = new char[maxinlen];
            {
                int orglen = aes.decrypt(encryptBuffer, encryptSize, orgdata);
                printf("decryptWithCrypto++(hex)=");
                dump(orgdata, orglen);
            }
            delete [] orgdata;
        }
        
        printf("encryptBuffer(hex)=");
        dump(encryptBuffer, encryptSize);
        
        {
            // encrypt.
            int maxoutlen = aes.getCipherLen(decryptSize);
            char * outdata = new char[maxoutlen];
            int outlen = 0;
            {
                outlen = aes.encrypt(decryptBuffer, decryptSize, outdata);
                printf("encryptWithCrypto++(hex)=");
                dump(outdata, outlen);
            }
            delete [] outdata;
        }
        
        delete [] decryptBuffer;
        delete [] encryptBuffer;
        
        
    }

    return 0;
}
Пример #25
0
TEST(AESTest, aes_test)
{
  static const struct { 
    int keylen;
    unsigned char key[32], pt[16], ct[16];
  } tests[] = {
    { 16,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, 
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 
        0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }
    }, { 
      24,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 },
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 
        0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 }
    }, {
      32,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 
        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f },
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 
        0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }
    }
  };

  AES *tf;

  unsigned char tmp[2][16];
  size_t i;
  int y;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
    tf = new AES(tests[i].key, tests[i].keylen);

    tf->Encrypt(tests[i].pt, tmp[0]);
    tf->Decrypt(tmp[0], tmp[1]);
    if (memcmp(tmp[0], tests[i].ct, 16) != 0 || memcmp(tmp[1], tests[i].pt, 16) != 0) {
      delete tf;
      FAIL() << "Test vector " << i;
    }

    /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
    for (y = 0; y < 16; y++) tmp[0][y] = 0;
    for (y = 0; y < 1000; y++) tf->Encrypt(tmp[0], tmp[0]);
    for (y = 0; y < 1000; y++) tf->Decrypt(tmp[0], tmp[0]);
    for (y = 0; y < 16; y++) if (tmp[0][y] != 0) {delete tf; FAIL() << "Encrypt/Decrypt zeros failed";}

    delete tf;
  }
  SUCCEED();
}
Пример #26
-1
int main(int argc, char **argv) {
	if(argc < 3) {
		printf("USAGE: aes KEY PLAINTEXT\n");
		return 1;
	}

	byte *key;
	uint *ct, *pt;
	uint keySize = stringToByteArray(argv[1], &key);
	uint ptSize  = stringToByteArray(argv[2], &pt);

	if(keySize != 16 && keySize != 24 && keySize != 32) {
		printf("Invalid AES key size.\n");
		return 1;
	}

	if(ptSize % 4 != 0) {
		printf("Plaintext size must be a multiple of AES block size.\n");
		return 1;
	}
	
	ct = (uint *)malloc(ptSize*sizeof(uint));

	AES *aes = new AES();
	aes->makeKey(key, keySize << 3, DIR_ENCRYPT);

	for(uint i = 0; i < ptSize; i += 4) {
		aes->encrypt(pt + i, ct + i);
	}

	printHexArray(ct, ptSize);

	return 0;
}