I have been working on getting the sha1() function working from openssl/sha.h however I am getting random output and some warning. I have read quite a bit and tried some of the example codes but I get warning on all of it and it doesn't display correctly.
Here is code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
const unsigned char data[] = "Hello, World";
unsigned long length = sizeof(data);
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(data, length, hash);
printf("%02x \n", hash);
return 0;
}
Below is the warning I am getting:
sha.c: In function ‘main’:
sha.c:12: warning: ‘SHA1’ is deprecated (declared at /usr/include/openssl/sha.h:124)
sha.c:13: warning: format ‘%02x’ expects type ‘unsigned int’, but argument 2 has type ‘unsigned char *’
sha.c:13: warning: format ‘%02x’ expects type ‘unsigned int’, but argument 2 has type ‘unsigned char *’
When I run it and I get the output:
62652b34
Any help would be great!
It also took me a while before I figured it all out. The best way is to use EVP, it provides generic functions for almost everything.
#include <openssl/evp.h>
You need to call this im main before calling you hash function. To initialize your hashes. Otherwise openssl will complain that the algorithm is not available.
OpenSSL_add_all_algorithms();
mode must be "SHA256", "SHA512", "SHA1" as string.
dataToHash is the input, dataSize is the size of the input,
outHashed should already be allocated, the hash will be written there
unsigned int hash(const char *mode, const char* dataToHash, size_t dataSize, unsigned char* outHashed) {
unsigned int md_len = -1;
const EVP_MD *md = EVP_get_digestbyname(mode);
if(NULL != md) {
EVP_MD_CTX mdctx;
EVP_MD_CTX_init(&mdctx);
EVP_DigestInit_ex(&mdctx, md, NULL);
EVP_DigestUpdate(&mdctx, dataToHash, dataSize);
EVP_DigestFinal_ex(&mdctx, outHashed, &md_len);
EVP_MD_CTX_cleanup(&mdctx);
}
return md_len;
}
A use example (this is not tested, I use the above code in a c++ wrapper)
const char *inData = "test data2";
unsigned char outHash[20]; // output is already allocated
hash("SHA1", inData, 10, outHash);
You shouldn't use the SHA1 method directly it is deprecated (your code could blow up with the next version).
If you want to use your version you need to print each char as hex:
int i;
for(i=0; i<SHA_DIGEST_LENGTH; i++) {
printf("%02x", hash[i]);
}
You can't dump the entire buffer that way. you need to loop it, such as below. The value you're getting for your output is actually the address of the hash buffer, which is clearly not what you're looking for. You want the hex-bytes in the buffer dumped as text
So...
int main()
{
const unsigned char data[] = "Hello, World";
unsigned long length = sizeof(data);
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(data, length, hash);
int i=0;
for (;i< sizeof(hash)/sizeof(hash[0]);++i)
printf("%02x \n", hash[i]);
return 0;
}
Regarding your warnings, the deprecation is because this interface is out-dated for performing the crypto-op you're attempting (SHA1). There are newer interfaces in OpenSSL that are current. Consider the EVP interface specifically.
printf("%02u \n", hash);
Remove warnings by printing unsigned char
Related
I want to store data in different files. Therefore I want to create files as follows: data_1.log, data_2.log, ..., data_N.log. The appendix .log is not necessary but would be nice. All my approaches failed so far. Here is one sample that is probably close to what I need:
#include <stdio.h>
#include <string.h>
char get_file_name(int k){
int i, j;
char s1[100] = "logs/data_";
char s2[100];
snprintf(s2, 100, "%d", k);
for(i = 0; s1[i] != '\0'; ++i);
for(j = 0; s2[j] != '\0'; ++j, ++i){
s1[i] = s2[j];
}
s1[i] = '\0';
return s1;
}
int main(){
char file_name[100];
for(int k=0; k<10; k++){
// Get data
// ...
// Create filename
strcpy(file_name, get_file_name(k));
printf("%s", file_name);
// fp = fopen(file_name, "w+");
// Write data to file
// print_results_to_file();
// fclose(fp);
}
return 0;
}
At the moment I get the following errors which I don't understand:
string.c: In function ‘get_file_name’:
string.c:14:12: warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]
return s1;
^~
string.c:14:12: warning: function returns address of local variable [-Wreturn-local-addr]
string.c: In function ‘main’:
string.c:24:27: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(file_name, get_file_name(k));
^~~~~~~~~~~~~~~~
In file included from string.c:2:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^~~~~~
Is there a more simpler way to create such filenames? I can't believe that there isn't one.
There are various issues with this code and rather than correcting them one by one here’s an alternative approach. It’s not the only one but it’s simple and should be easy to understand and adapt:
#include <stdio.h>
void get_file_name(int k, char* buffer, size_t buflen) {
snprintf(buffer, buflen, "logs/data_%d.log", k);
}
int main() {
const size_t BUFLEN = 50;
char file_name[BUFLEN];
for (int i = 0; i < 10; i++) {
get_file_name(i, file_name, BUFLEN);
printf("%s\n", file_name);
// Code for writing to file.
}
}
A few details:
Rather than attempting to return (pointers to) memory, this function passes a buffer that is written to. It’s up to the caller to ensure that the buffer is big enough (this is always the case here, but if the actual filenames are longer, you should add logic that inspects the return value of snprintf and performs appropriate error handling).
The actual logic of the function requires only a single call to snprintf, which already performs everything you require, so it’s unclear whether having a separate function is even necessary or helpful.
The above uses variable-length arrays. If you want to ensure constant buffers, you can use a #define instead of a const size_t variable for the buffer length. However, using a variable-length array here is fine, and some compilers even convert it into a constant array.
As mentioned in comments, it’s important that you (a) read and understand the documentation of the functions you’re using, and (b) read and understand the compiler error messages.
The function get_file_name has return type char
char get_file_name(int k){
but it returns an object of type char *
char s1[100] = "logs/data_";
//...
return s1;
Moreover the returned pointer points to a local array s1 that will not alive after exiting the function.
In this call
strcpy(file_name, get_file_name(k));
the type of the second argument (that is char according to the function get_file_name declaration) shall be char *.
There is neither the function print_results_to_file declaration nor its definition.
According to the C Standard the function main without parameters shall be declared like
int main( void )
I would write the function get_file_name the following way
#include <stdio.h>
#include <string.h>
char * get_file_name( char *file_name, size_t n, size_t padding )
{
const char *common_part = "logs/data_";
snprintf( file_name, n, "%s%zu", common_part, padding );
return file_name;
}
int main( void )
{
enum { N = 100 };
char file_name[N];
for ( size_t i = 0; i < 10; i++ ) puts( get_file_name( file_name, N, i ) );
}
The program output is
logs/data_0
logs/data_1
logs/data_2
logs/data_3
logs/data_4
logs/data_5
logs/data_6
logs/data_7
logs/data_8
logs/data_9
There are several problems with your code, but the biggest one is that you are trying to return a pointer to a local variable from get_file_name.
This is a big no no since the memory allocated for char s1[100] in get_file_name is freed immediately after return.
The rest of the errors are because you forgot the * in char get_file_name(int k).
There are several possible solutions:
Pass in a char array for the function to fill.
Use a global variable (This is considered a bad practice).
Dynamically allocate the memory.
Make the local variable static (this is a bit hacky, but legal)
Your errors are easily explained:
get_file_name should return a char but you create a char[] and return this(it isthe same as char*)
get_file_name returns the adress of an array that is created in the function itself. After the function ends, the array may be overwritten. Add the array as parameter or use malloc
strcpy does not work because it expects a char* (char[]) and not a char. get_file_name returns a char.
print_results_to_file is not defined. You may need to include other files you use in the program (e.g. if the function is implemented in a file func.c the prototype should be in a file called func.h that is included via #include "func.h".
expected ‘int’ but argument is of type ‘char *’
dont know how to correct, any suggestion
#include <stdio.h>
int my_strncmp(char const *s1, char const *s2, int n);
int main (int ac, char **ag) {
char result;
if (ac == 4) {
result = my_strncmp(ag[1], ag[2], ag[3]);
printf("%d\n", result);
}
return(0);
}
You need to convert ag[3] (of type char * / string) to an integer.
Have a look at strtol() and its brethren. With atoi() exists a simpler function, which however is not as robust and versatile. That is why I would recommend getting into the habit of using strtol() et al., always.
Sidenote, "n" parameters are usually made size_t (unsigned) instead of int. (Compare strncmp()). You'd use strtoul() then.
The last parameter of my_strncmp is defined as an int n, yet when it is called in main the third parameter is char * type
in here,
int my_strncmp(char const *s1, char const *s2, int n);
the last part is int n
result = my_strncmp(ag[1], ag[2], ag[3]);
but here what you are passing ag[3] is of type char
hope this helps..
I am currently trying to do my own shell, and it has to be polyglot.
So I tryed to implement a function that reads the lines in a .txt file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = *line;
i++;
}
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
}
I am on win7 but I compile with gcc on a VM.
I have a warning saying :
format'%s' expects argument of type 'char *', but argument 2 (and 3) has type 'int' [-Wformat=]
I tried to execute the prog with %d instead of %s and it prints numbers.
I don't understand what converts my aMsg into a int.
My try.txt file is just :
Hi
Quit
The contents of your text file have nothing to do with the warning, which is generated by the compiler before your program ever runs. It is complaining about this statement:
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
Global variable aMsg is an array of char, so aMsg[HI] designates a single char. In this context its value is promoted to int before being passed to printf(). The %s field descriptor expects an argument of type char *, however, and GCC is smart enough to recognize that what you are passing is incompatible.
Perhaps you had in mind
printf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT]);
or the even the equivalent
printf("%s\n%s\n", aMsg + HI, aMsg + QUIT);
but though those are valid, I suspect they won't produce the result you actually want. In particular, given the input data you specified and the rest of your program, I would expect the output to be
HQ
Q
If you wanted to read in and echo back the whole contents of the input file then you need an altogether different approach to both reading in and writing out the data.
Let's take a closer look on the problematic line:
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
The string you would like to print expects 2 string parameters. You have aMsg[HI] and aMsg[QUIT]. These two are pointing to a char, so the result is one character for each. All char variables can be interpreted as a character or as a number - the character's ID number. So I assume the compiler resolves these as int types, thus providing you that error message.
As one solution you merely use %c instead of %s.
However, I suspect you want to achieve something else.
I'm completely guessing, but I think what you want is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char *aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = malloc(strlen(line)+1);
strcpy(aMsg[i], line);
i++;
}
fclose(file);
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
free(aMsg[HI]);
free(aMsg[QUIT]);
return 0;
}
I am trying to generate MD5 hash for an string "Hello World" using the original/untouched md5.h and md5c.c from http://www.arp.harvard.edu. But my result differs from all md5 online tools i have tested. Whats wrong this this code? Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "md5.h"
void MD5hash(unsigned char *data, unsigned int dataLen, unsigned char *digest) {
MD5_CTX c;
MD5Init(&c);
MD5Update(&c, data, dataLen);
MD5Final(digest, &c);
}
int main(int argc, const char * argv[]) {
unsigned char digest[16];
const char *s = "Hello World";
unsigned int l = (unsigned int)strlen(s);
MD5hash((unsigned char *)s, l, digest);
for(int i = 0; i < 16; ++i)
printf("%02x", digest[i]);
return 0;
}
// My result: f2877a72c40494318c4b050bb436c582
// But online tools output: b10a8db164e0754105b7a99be72e3fe5
As #vipw mentioned there is an issue with padding. This MD5 implementation does not correctly manage padding for message sizes that are not a multiple of a MD5 block size (512-bit / 64 bytes).
To fix it on your side, replace:
const char *s = "Hello World";
by
const char s[64] = "Hello World";
EDIT:
There was a second issue related to portability in this MD5 implementation. In md5.h there is this type alias:
typedef unsigned long int UINT4;
On a Linux x86_64 system (which you are using), this must be changed to this:
typedef unsigned int UINT4;
You have an issue with padding. The MD5 Hash algorithm works on 512-bit blocks. When your final block is less than 512 bits, it needs to be padded. In your example, the first block is also the last block because it's less than 512 bits.
The padding is format is called Merkle–Damgård construction.
You can find some pseudo code that includes padding here.
I am writing a program that passes text to a library function.
This function expects the text parameter to be of type unsigned char*.
So how can I properly pass a String to that function? I fail at converting an existing char* to unsigned char* and writing a new value into an unsigned char* variable via strncpy also didn't work.
Edit:
Here is a small example:
That is the function I need to call:
int count (void *index, uchar *pattern, uint length, uint *numocc);
This is what I have in my code:
count(index,?argv[2]?, length, numocc);
You can do typecasting with (unsigned char*). I am posting a small example may be it help you(read comments):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func(unsigned char* str){ // argument should be unsigned char*
printf("\n In side fun: %s\n", str);
}
int main(){
char* s = "your_name"; // s is char*
func((unsigned char*)s); // notice type casting
return 1;
}
and it works:
~$ gcc x.c -Wall
~$ ./a.out
In side fun: your_name
~$
EDIT:
count(index, (uchar*)argv[2], length, numocc);
^ typecast (uchar*)
uchar* may be a typedef ed in your code like:
typedef unsigned char* uchar*