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()
{
}
Glorfindel
5781 gold badge7 silver badges18 bronze badges
asked Feb 10, 2019 at 2:39
2
  • instead of printing it, put it in an array of char - you'll need an array 64 long of course Commented Feb 10, 2019 at 6:11
  • hello jaromanda,thank u for ur suggestion,i can not copy from the output of printhash function Commented Feb 10, 2019 at 20:06

2 Answers 2

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)
{}
Glorfindel
5781 gold badge7 silver badges18 bronze badges
answered Feb 10, 2019 at 23:25
1
  • this is the code that worked for me Commented Feb 10, 2019 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!

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.