简体   繁体   中英

SHA256 using Openssl causes segmentation fault

I'm trying to encrypt files using AES and based on forward secrecy principe by computing the new key of encryption which is the hash of the old key. So I'm using the openssl implementation for hash function SHA256. First I wanted to test the feasibility of this with this simple code :

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

 int main()
 {
     unsigned char *key =(unsigned char *)"01234567890123456789012345678901";
     SHA256(key, strlen(key), key);
     return 0;
  }

But a segmentation fault occurs what can be the reason ?

Your string literal is placed in read-only memory and when openssl tries to write to it, your program gets the segmentation fault.

Language-wise, attempting to modify string literals is causing undefined behavior.

Either create a buffer for your input key or create a new buffer for the output.

C string literals are effectively char const* (although they're char * , technically, for compatibility reasons). You should not write to them. If you do, the behavior of your program will be undefined.

Anyway, SHA256 from #include <openssl/sha.h> is:

unsigned char *SHA256(const unsigned char *d, size_t n,unsigned char *md);

So to use it, you should do something like:

char const *key = "01234567890123456789012345678901";
unsigned char buf[256/CHAR_BIT]; //or SHA256_DIGEST_LENGTH
SHA256((unsigned char const*)key, strlen(key), buf);

You can then print the result with:

 for(int i=0;i<sizeof(buf);i++)
     printf("%.2hhx", buf[i]);

(assuming 8 bit chars).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM