I'm trying to compute a SHA256 hash of the string iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9
When I run my C++ code, I get a string that's not even a valid SHA256 hash. However, when I run echo -n iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9 | openssl sha256, I get the correct hash. Here's my C++ code:
#include <iostream>
#include <time.h>
#include <sstream>
#include <string>
#include <iomanip>
#include <typeinfo>
#include <openssl/sha.h>
#include <cstdio>
#include <cstring>
std::string hash256(std::string string) {
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, string.c_str(), std::strlen(string.c_str()));
SHA256_Final(digest, &ctx);
char mdString[SHA256_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
std::sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
return std::string(mdString);
}
int main(int argc, char *argv[])
{
const char *hash = hash256("iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9").c_str();
std::cout << hash << std::endl;
return 0;
}
Another thing to note: When I run my code in an online compiler, such as Coliru, I get the correct hash. I am compiling with G++ on Cygwin with OpenSSL version OpenSSL 1.0.1g 7 Apr 2014
As pointed out by #Alan Stokes, you have Undefined Behavior due to a dangling reference to the internal structure of the string. Change your declaration of hash in main:
std::string hash = hash256("...");
Related
Im trying to convert the command line argument(*argv[]) to an integer using the atoi function
int main(int argc, char *argv[]) {
This is my attempt
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[]) {
int x = 0;
for ( x=0; x < argc; x++ )
{
int x = atoi(argv[1]);
cout << x;
}
return 0;
}
However this returns 0 and im unsure why. Thankyou
It's hard to say having the arguments you pass to your program, but there are few problems here.
Your loop goes from 0 to argc, but your inside your loop you always use argv[1], if you didn't pass any arguments you're going out of bounds, because argv[0] is always the path to your executable.
atoi is a function from C, and when it fails to parse it's argument as an int, it returns 0, replace it with std::stoi, and you will get and execption if the conversion failed. You can catch this exception with try/catch, and then check the string that you tried to convert to int.
Well, this
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[]) {
int x = 0;
for (x = 0; x < argc; x++)
{
cout << argv[x];
}
return 0;
}
just prints the path to the .exe, the path is a string, it has no numbers. And as I understood from my "research" about command line arguments, you need to use your program through a command line, a terminal, to initialise the argv argument.
Link : https://www.tutorialspoint.com/cprogramming/c_command_line_arguments.htm
Also, as I understood at least, the argv[0] is always the path of the .exe
I hope I will be of some help, if I am mistaken at something, pls tell me where and I will correct my self by editing the answer
#include <graphics.h>
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
int gd = DETECT,gm;
/* warning deprecated convesion from string to char* [wWrite-strings] */
initgraph(&gd,&gm, "C:\\TURBOC3\\BGI");
circle(300,300,50);
closegraph();
getch();
return 0;
}
Store the string in a modifiable array:
char bgi[] = "C:\\TURBOC3\\BGI";
initgraph(&gd,&gm,bgi);
I am looking for some function or a way that would return HMAC SHA256 hash in C++ using secret key. I have seen documentation of Crypto++ and OpenSSL but it does not accept an extra parameter of secret key for computation. Can someone help me by providing some info, code snippets or links.
You can use POCO library
Sample code:
class SHA256Engine : public Poco::Crypto::DigestEngine
{
public:
enum
{
BLOCK_SIZE = 64,
DIGEST_SIZE = 32
};
SHA256Engine()
: DigestEngine("SHA256")
{
}
};
Poco::HMACEngine<SHA256Engine> hmac{secretKey};
hmac.update(string);
std::cout << "HMACE hex:" << Poco::DigestEngine::digestToHex(hmac.digest()) << std::endl;// lookout difest() calls reset ;)
Sample integration with POCO using cmake install:
mkdir build_poco/
cd build_poco/ && cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./install ../poco/
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.8)
PROJECT(SamplePoco)
SET(CMAKE_CXX_STANDARD 14)
SET(SOURCE_FILES
src/main.cpp
)
SET(_IMPORT_PREFIX lib/build_poco/install)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoFoundationTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoNetTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoJSONTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoXMLTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoCryptoTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoUtilTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoNetSSLTargets.cmake)
ADD_EXECUTABLE(SamplePoco ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(SamplePoco
Poco::Foundation
Poco::Crypto
Poco::Util
Poco::JSON
Poco::NetSSL
)
TARGET_INCLUDE_DIRECTORIES(SamplePoco PUBLIC src/)
Sample implementation used here: https://github.com/gelldur/abucoins-api-cpp
Following is a sample of function to generate SHA256-HMAC using Crypto++
#include <string>
#include <string_view>
#include <cryptopp/filters.h>
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::HashFilter;
#include <cryptopp/hmac.h>
using CryptoPP::HMAC;
#include <cryptopp/sha.h>
using CryptoPP::SHA256;
std::string CalcHmacSHA256(std::string_view decodedSecretKey, std::string_view request)
{
// Calculate HMAC
HMAC<SHA256> hmac(reinterpret_cast<CryptoPP::byte const*>(decodedSecretKey.data()), decodedSecretKey.size());
std::string calculated_hmac;
auto sink = std::make_unique<StringSink>(calculated_hmac);
auto filter = std::make_unique<HashFilter>(hmac, sink.get());
sink.release();
StringSource(reinterpret_cast<CryptoPP::byte const*>(request.data()), request.size(), true, filter.get()); // StringSource
filter.release();
return calculated_hmac;
}
#include <iostream>
int main() {
std::cout << CalcHmacSHA256("key", "data");
}
The source is CME iLink2 specification
For consistency, following is a sample of function to generate SHA256-HMAC using OpenSSL
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <string>
#include <string_view>
#include <array>
std::string CalcHmacSHA256(std::string_view decodedKey, std::string_view msg)
{
std::array<unsigned char, EVP_MAX_MD_SIZE> hash;
unsigned int hashLen;
HMAC(
EVP_sha256(),
decodedKey.data(),
static_cast<int>(decodedKey.size()),
reinterpret_cast<unsigned char const*>(msg.data()),
static_cast<int>(msg.size()),
hash.data(),
&hashLen
);
return std::string{reinterpret_cast<char const*>(hash.data()), hashLen};
}
For the record, I like Crypto++ better as in case of Crypto++ generated binary is smaller. The drawback is that Crypto++ does not have a CMake module.
OpenSSL docs for HMAC, clearly state the requirement of a 'key' as part of context initialization.
int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len,
const EVP_MD *md, ENGINE *impl);
HMAC() computes the message authentication code of the n bytes at d
using the hash function evp_md and the key key which is key_len bytes
long.
You can use cpp-cryptlite to generate HMAC SHA256 hash, Following is the code snippet:
std::string src_str = "abcdefg";
std::string secret_key = "xxxxxx"; // this value is an example
boost::uint8_t digest[32]; // cryptlite::sha256::HASH_SIZE
cryptlite::hmac<cryptlite::sha256>::calc(src_str, secret_key, digest);
// and digest is the output hash
I had to modify #DmytroOvdiienko's answer a bit to get hexadecimal output:
#include <iomanip>
...
std::string CalcHmacSHA256(std::string_view decodedKey, std::string_view msg)
{
std::array<unsigned char, EVP_MAX_MD_SIZE> hash;
unsigned int hashLen;
HMAC(
EVP_sha256(),
decodedKey.data(),
static_cast<int>(decodedKey.size()),
reinterpret_cast<unsigned char const*>(msg.data()),
static_cast<int>(msg.size()),
hash.data(),
&hashLen
);
std::stringstream out;
for (unsigned int i=0; i < hashLen; i++) {
out << std::setfill('0') << std::setw(2) << std::right << std::hex << (int)hash.data()[i];
}
return out.str();
}
int main(int, char**) {
std::string key = "ESiFg448MqOmhQyxbt6HEHHPnAA1OE8nX0o9ANIVMIvWLISQS0MivDrkZvnBxMEI";
std::string msg = "foo";
std::string_view key_view{key};
std::string_view msg_view{msg};
std::cout << CalcHmacSHA256(key_view, msg_view) << std::endl;
}
The <iomanip>, setfill, setw, right are needed to make sure single-digit hex values are prefixed with a 0. An alternative is to use boost:
#include <boost/format.hpp>
...
out << boost::format("%02x") % (int)hash.data()[i];
I'm trying to get the mac address of a user, then store it in a string. I've got the mac address get function down, however I'm having a bit of trouble storing the final value of the mac address into a string. Can anybody help out?
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <rpc.h>
#include <rpcdce.h>
#include <string>
#pragma comment(lib, "rpcrt4.lib")
using namespace std;
static void PrintMACaddress(unsigned char MACData[])
{
printf("%02X-%02X-%02X-%02X-%02X-%02X\n", MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
}
static void GetMACaddress(void)
{
unsigned char MACData[6];
UUID uuid;
UuidCreateSequential(&uuid);
for (int i=2; i<8; i++)
MACData[i - 2] = uuid.Data4[i];
PrintMACaddress(MACData);
}
int main()
{
GetMACaddress();
system("pause");
}
Basiclly, I need the final result into a string value
Sorry if this is too broad.
You can use snprintf() function to convert to string:
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%02X-%02X-%02X-%02X-%02X-%02X",
MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
std::string str = buffer;
where i can find an sample code for hypertable or else can any one post an sample for hypertable with c++
If you meant the source code for hypertable
otherwise here is the manual
You can use this HQL tutorial or look at this example
see this:: http://blog.hypertable.com/
and download hypertable project :: http://www.hypertable.org/
#ifndef BOOST_FOREACH
#define BOOST_FOREACH 0
#endif
#include "Common/Compat.h"
#include "Common/System.h"
#include <arpa/inet.h>
#include <iostream>
#include <fstream>
#include "ThriftBroker/Client.h"
#include "ThriftBroker/gen-cpp/HqlService.h"
#include "ThriftBroker/ThriftHelper.h"
#include "ThriftBroker/SerializedCellsReader.h"
using namespace Hypertable;
using namespace Hypertable::ThriftGen;
int main (int argc, char **argv)
{
Thrift::Client *client = new Thrift::Client("localhost", 38080);
if (!client->namespace_exists("/"))
{
delete client;
return 0;
}
Namespace ns = client->namespace_open("/");
HqlResult result;
client->hql_query(result, ns, "select * from foo");
std::cout << result << std::endl;
client->namespace_close(ns);
delete client;
return 0;
}
将其和/opt/hypertable/current/include/ThriftBroker/gen-cpp文件夹下的
Client_constants.cpp、Client_types.cpp、ClientService.cpp、Hql_constants.cpp、Hql_types.cpp、HqlService.cpp一起编译