c++ md5加密算法
时间: 2024-01-31 11:10:27 浏览: 41
以下是C++中实现MD5加密算法的示例代码:
```cpp
#include <iostream>
#include <string>
#include <cstring>
#include <openssl/md5.h>
std::string md5(const std::string& input) {
unsigned char digest[MD5_DIGEST_LENGTH];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, input.c_str(), input.length());
MD5_Final(digest, &context);
char md5String[33];
for (int i = 0; i < 16; ++i) {
sprintf(&md5String[i * 2], "%02x", (unsigned int)digest[i]);
}
return std::string(md5String);
}
int main() {
std::string input = "Hello World";
std::string encrypted = md5(input);
std::cout << "MD5 encrypted string: " << encrypted << std::endl;
return 0;
}
```
这段代码使用了OpenSSL库中的MD5函数来计算输入字符串的MD5值。首先,我们需要包含必要的头文件,并定义一个md5函数来执行加密操作。在md5函数中,我们首先声明一个用于存储MD5结果的unsigned char数组和一个MD5_CTX结构体。然后,我们使用MD5_Init函数初始化MD5上下文,使用MD5_Update函数将输入字符串添加到MD5计算中,最后使用MD5_Final函数获取最终的MD5结果。接下来,我们将MD5结果转换为字符串形式,并返回该字符串。
在main函数中,我们定义了一个输入字符串,并调用md5函数来获取其MD5加密结果。最后,我们将加密结果输出到控制台。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)