Calculate SHA-256 programmatically (c++ and golang)

By | September 9, 2022

SHA-256 is 256 bit hash value calculated by SHA-2 (Secure Hash Algorithm 2). SHA-256 is used in some of the multiple well known authentication and encryption protocols, including SSL, TLS, IPsec, SSH, and PGP. Also it is used for secure password hashing and cryptocurrency transaction verification. Here is c++ example how to calculate SHA-256 has of string using openssl API. Templates of hash functions are defined in sha.h openssl include file.
Source:


#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
void hex2str(unsigned char * binary, int len, char * hexstr);
int main(int n, char * args[])
{
   if(n < 2)
   {
      printf("String argument is required to calculate sha1\n");
      return -1;
   }
   unsigned char * md;
   md = new unsigned char[SHA256_DIGEST_LENGTH + 1];
   unsigned char * md1 = SHA256((const unsigned char*)args[1], strlen(args[1]), md);
   char * hexstr = new char[2*SHA256_DIGEST_LENGTH + 1];
   hex2str(md1, SHA256_DIGEST_LENGTH, hexstr);
   printf("SHA256 of %s is %s\n", args[1], hexstr);
   delete[] md;
   delete[] hexstr;
   return 0;
}
void hex2str(unsigned char * binary, int len, char * hexstr)
{
   memset(hexstr, 2*SHA256_DIGEST_LENGTH+1, 0);
   for(int i =0; i < SHA256_DIGEST_LENGTH; i++)
   {
      sprintf(&hexstr[i*2], "%02x", binary[i]);
   }
}

Compilation:


# g++ -g -o calc_sha256 calc_sha256.cpp -lssl -lcrypt

Execution:


# ./calc_sha256 qwerty
SHA256 of qwerty is 65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5

Compare with openssl command:


# echo -n qwerty | openssl sha256
(stdin)= 65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5

Now Go example.


package main

import (
   "crypto/sha256"
   "fmt"
   "os"
)

func main() {
   argLen := len(os.Args)
   if argLen == 1 {
      fmt.Println("Specify string as an argument to calculate its SHA256")
      os.Exit(-1)
   }
   byteArray := []byte(os.Args[1])
   fmt.Printf("%x", sha256.Sum256(byteArray))
}

Compilation:


C:\projects\Go\hash>go build sha256.go

Execution:


C:\projects\Go\hash>sha256.exe qwerty
65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5

Leave a Reply

Your email address will not be published. Required fields are marked *