问题
AES has maximum block size of 128, and key sizes like 128, 196 & 256.
I have implemented the aes algorithm like so:
int main()
{
unsigned char key[KEY_128] = "very strong key";
unsigned char plaintext[16] = "this is a test";
unsigned char ciphertext[16];
unsigned char decptext[16];
aes_ctx_t *ctx;
virtualAES::Initialize();
ctx = virtualAES::AllocateCTX(key, sizeof(key));
virtualAES::Encrypt(ctx, plaintext, ciphertext);
cout << "encrypted: " << ciphertext << endl;
virtualAES::Encrypt(ctx, ciphertext, decptext);
cout << "decrypted: " << decptext << endl;
return 0;
}
but I want to encrypt larger data than 128bits, for example string that's 512 bits long. How to achieve?
回答1:
I posted this answer elsewhere, but as it applies here as well, here you go:
I am more familiar with C#, which has several modes of encryption exposed through the System.Security.Cryptography namespace. However I know how Cipher Block Chaining works. I'll explain it to you, but keep in mind it is really easy to mess up crypto, so this is informational only, and I hope you will find a library that does what you need done.
With cipher block chaining (CBC) here is what you do. Take your data and break it into block sizes. 128 bits is 16 bytes, so there you go. If you have less than 16 bytes in your last block, you must pad. The commonest way I know of is PKCS7 padding, which means for example if you need 3 bytes of padding at the end of your last block, you would add 0x03, 0x03, 0x03 to make it a full block.
So now you are ready to encrypt. You should have an initialization vector (IV) to start off with. Bitwise XOR that IV with your first block of plain text. Then encrypt the result the way you normally would encrypt a single block of data (ECB mode). The result is your first block of cipher text. But it is also equivalent to the IV for the next block you want to encrypt. Bitwise XOR it with the second block and encrypt. Take that encrypted block, record it, and also use it to XOR with the third block. And so on.
This process makes it so that the exact same text appearing, let's say 5 times in a document will look totally different each time it appears. So it adds more security. Despite this, the IV does not need to be kept secret at all. Passwords and salts do, IVs do not.
来源:https://stackoverflow.com/questions/31777362/c-aes-encrypt-bigger-string-than-128bits