sha256c++代码
时间: 2023-10-26 20:05:45 浏览: 59
以下是一个简单的示例代码,用于计算字符串的 SHA256 哈希值:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
void sha256(const char* string, unsigned char* hash) {
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
}
int main() {
const char* string = "Hello, world!";
unsigned char hash[SHA256_DIGEST_LENGTH];
sha256(string, hash);
printf("SHA256 hash: ");
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
printf("%02x", hash[i]);
}
printf("\n");
return 0;
}
```
相关问题
C++sha256算法
以下是一个使用C++实现的SHA256算法的示例代码:
```cpp
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <openssl/sha.h>
std::string sha256(const std::string& input) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, input.c_str(), input.length());
SHA256_Final(hash, &sha256);
std::stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
return ss.str();
}
int main() {
std::string input = "Hello, world!";
std::string hash = sha256(input);
std::cout << "SHA256 hash of \"" << input << "\" is: " << hash << std::endl;
return 0;
}
```
这段代码使用了OpenSSL库中的SHA256函数来计算给定输入的SHA256哈希值。它将输入字符串转换为字节数组,并使用SHA256_Init、SHA256_Update和SHA256_Final函数来计算哈希值。最后,它将哈希值转换为十六进制字符串并返回。
c++ sha256
在C++中,可以使用各种库来计算SHA-256哈希。以下是使用Crypto++库计算SHA-256哈希的示例代码:
首先,你需要安装Crypto++库。你可以通过在终端中运行以下命令来安装Crypto++:
```
sudo apt-get install libcrypto++-dev
```
然后,你可以使用以下示例代码来计算SHA-256哈希:
```cpp
#include <iostream>
#include <string>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
std::string sha256(const std::string& input) {
CryptoPP::SHA256 hash;
std::string digest;
CryptoPP::StringSource(input, true,
new CryptoPP::HashFilter(hash,
new CryptoPP::HexEncoder(new CryptoPP::StringSink(digest))));
return digest;
}
int main() {
std::string input = "Hello, World!";
std::string hash = sha256(input);
std::cout << "Input: " << input << std::endl;
std::cout << "SHA-256 Hash: " << hash << std::endl;
return 0;
}
```
在上述示例中,我们定义了一个名为sha256的函数,它接受一个输入字符串并返回其SHA-256哈希值。在主函数中,我们使用"Hello, World!"作为输入字符串,并打印出计算得到的SHA-256哈希值。
请注意,这只是一个基本的示例,实际应用中可能需要更多的错误处理和输入验证。同时,还有其他的C++库可用于计算SHA-256哈希,例如Botan、OpenSSL等。你可以根据自己的需求选择适合的库进行使用。