VS2015 環境,需在一天內完成:
1. AES 加密解密(對稱加密)
2. 單表替換密碼(古典密碼學)
要求代碼簡單易懂,適合初學者。
#include
#include
#include
void aes128_ecb_encrypt(const unsigned char* key, const unsigned char* in, unsigned char* out) {
AES_KEY enc_key;
AES_set_encrypt_key(key, 128, &enc_key);
AES_encrypt(in, out, &enc_key);
}
void aes128_ecb_decrypt(const unsigned char* key, const unsigned char* in, unsigned char* out) {
AES_KEY dec_key;
AES_set_decrypt_key(key, 128, &dec_key);
AES_decrypt(in, out, &dec_key);
}
int main() {
unsigned char key[16] = "0123456789abcdef";
unsigned char plain[16] = "HelloAESWorld!!!";
unsigned char cipher[16], decrypted[16];
aes128_ecb_encrypt(key, plain, cipher);
aes128_ecb_decrypt(key, cipher, decrypted);
printf("Plain: %s\n", plain);
printf("Cipher: ");
for(int i=0;i<16;i++) printf("%02x", cipher[i]); puts("");
printf("Decryp: %s\n", decrypted);
return 0;
}
編譯:`g++ aes_demo.cpp -lcrypto -o aes_demo` (需安裝 OpenSSL 開發包)
#include
#include
#include
#include
std::string generate_key() {
std::string key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(key.begin(), key.end(), g);
return key; // 如 "QWERTYUIOPASDFGHJKLZXCVBNM"
}
std::string encrypt_substitution(const std::string& plain, const std::string& key) {
std::string cipher;
for (char c : plain) {
if (c >= 'A' && c <= 'Z') cipher += key[c - 'A'];
else if (c >= 'a' && c <= 'z') cipher += std::tolower(key[c - 'a']);
else cipher += c;
}
return cipher;
}
std::string decrypt_substitution(const std::string& cipher, const std::string& key) {
std::string plain;
for (char c : cipher) {
if (c >= 'A' && c <= 'Z') {
size_t pos = key.find(c);
if (pos != std::string::npos) plain += 'A' + pos;
else plain += c;
} else if (c >= 'a' && c <= 'z') {
size_t pos = key.find(std::toupper(c));
if (pos != std::string::npos) plain += 'a' + pos;
else plain += c;
} else plain += c;
}
return plain;
}