又是基于西工大的计算机课题a,ε=(´ο`*)))唉。
C++ 中有许多加密算法。以下是一些常见的加密算法和 C++ 中的实现方式:
1.对称加密算法:AES
对称加密使用相同的密钥进行加密和解密。AES(Advanced Encryption Standard)是一种流行的对称加密算法。
#include <iostream>
#include <openssl/aes.h>
int main() {
// 128位密钥
unsigned char key[16] = "0123456789abcdef";
// 待加密的数据
unsigned char input[16] = "hello world";
// 加密后的数据
unsigned char output[16];
AES_KEY aesKey;
AES_set_encrypt_key(key, 128, &aesKey);
AES_encrypt(input, output, &aesKey);
std::cout << "Encrypted: ";
for (int i = 0; i < 16; ++i) {
std::cout << std::hex << (int)output[i] << " ";
}
return 0;
}
2.非对称加密算法:RSA
非对称加密使用公钥进行加密,私钥进行解密,或者反过来。RSA 是一种常见的非对称加密算法。
#include <iostream>
#include <openssl/rsa.h>
int main() {
RSA *rsaKey = RSA_generate_key(2048, RSA_F4, nullptr, nullptr);
// 待加密的数据
const char *input = "hello world";
// 加密后的数据
unsigned char encrypted[256];
int encryptedLength = RSA_public_encrypt(strlen(input) + 1, (const unsigned char *)input, encrypted, rsaKey, RSA_PKCS1_PADDING);
std::cout << "Encrypted: ";
for (int i = 0; i < encryptedLength; ++i) {
std::cout << std::hex << (int)encrypted[i] << " ";
}
RSA_free(rsaKey);
return 0;
}
3.哈希算法:SHA-256
哈希算法用于生成数据的固定长度摘要。SHA-256 是一种常见的哈希算法。
#include <iostream>
#include <openssl/sha.h>
int main() {
// 待哈希的数据
const char *input = "hello world";
// 哈希结果
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256((const unsigned char *)input, strlen(input), hash);
std::cout << "SHA-256 Hash: ";
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
std::cout << std::hex << (int)hash[i];
}
return 0;
}
以上示例使用了 OpenSSL 库中的函数,确保你的项目中已经包含 OpenSSL 库,并通过适当的方式链接。在实际应用中,对于密码学和安全性的需求,建议使用专业的密码库,并根据特定情境谨慎选择加密算法。
基于目前知识的限制,敬请指正