0

I am using this code and I can not save the output of the hash function to an array of char. Can you help me how to do that?

#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{


}
2
  • instead of printing it, put it in an array of char - you'll need an array 64 long of course – Jaromanda X Feb 10 '19 at 6:11
  • hello jaromanda,thank u for ur suggestion,i can not copy from the output of printhash function – Amr Ahmed Feb 10 '19 at 20:06
1

This is the code that worked for me:

#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}
1
  • this is the code that worked for me – Amr Ahmed Feb 10 '19 at 23:26
0

Save to a character vector (64 characters + NULL):

void copyHash(char* buf, uint8_t* hash) {
  int i, j = 0;
  for (i = 0; i < 32; i++) {
    buf[j++] = "0123456789abcdef"[hash[i]>>4];
    buf[j++] = "0123456789abcdef"[hash[i]&0xf];
  }
  buf[j] = 0;
}

void setup()
{ 
  String FinalStr="1234567890";
  Sha256.init();
  Sha256.print(FinalStr);
  char buf[65];
  copyHash(buf, Sha256.result());
}

Cheers!

2
  • hello mikael,thank u 4 ur help,i will try and tell u the results,deeply appreciated – Amr Ahmed Feb 10 '19 at 20:19
  • I have tried and got different outputs "c775e7b757ede630cd0aa1113bd102661ab38829ca52a6422ab782862f268646 2f64612d9642afc666117f4d4fc87c17dba06ad091e1ce611f70020f2278337e" – Amr Ahmed Feb 10 '19 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.