EMSA_PSS_ENCODE with libssl - c

Hi I'm trying to use libssl to get some EMSA_PSS_ENCODING through the function RSA_padding_add_PKCS1_type1 in libssl, but I can't find nor docs nor solutions, so this is the example code I've written:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
FILE *error_file;
int main()
{
int lSize;
const unsigned char *string1= (unsigned char *)"The pen is on the table";
unsigned char *stringa=NULL;
int num = 64;
if ((stringa = (unsigned char *)OPENSSL_malloc(num)) == NULL)
fprintf(stderr,"OPENSSL_malloc error\n");
lSize = strlen((char *)string1);
fprintf(stdout,"string1 len is %u\n",lSize);
if(RSA_padding_add_PKCS1_type_1(stringa,num,string1,lSize) != 1)
fprintf(stderr,"Error: RSA_PADDING error\n");
error_file = fopen("libssl.log", "w");
ERR_print_errors_fp(error_file);
fclose(error_file);
fprintf(stdout,(char *)stringa);
fprintf(stdout,"\n");
}
The problem is that I get no output in stringa, I think the function RSA_padding_add.. should be initialized, but I can't find how to do it in the few doc at the openssl site.
Thanks

See http://www.openssl.org/docs/crypto/RSA_padding_add_PKCS1_type_1.html .
Try defining lSize to (int)strlen(string1) after string1 is set.
EDIT:
Allocate stringa.
unsigned char *stringa=malloc(num);

Related

How to understand if Heap is full and why malloc keeps return NULL?

As an exercise, currently I am working on a project: a personal text based database (hence a collection of (personal and not) data arranged in a file as a sort of "database") managed with C programming Language.
I thought to keep all the managing function on a .h file and the main functions (the one that interact with the user, owner of the database) in a .c file.
The .h file is not completed yet, but I am slowly testing each function to see if they work correctly.
In particular this one it is daunting me duo to the fact I cannot find the reason why heap gets full (if it really gets full...).
Here is the full code: (The interested function is called "initobj". Though I shared the full code thinking it could be useful to understand)
#include <time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#if defined(_WIN32)
#define PATH "C:\\Database\\"
#elif defined(_WIN64)
#define PATH "C:\\Database\\"
#elif defined(__linux__)
#define PATH "/Database/"
#else
#define PATH NULL
#endif
struct user{
unsigned int uid;
char *username;
char *password;
};
struct file{
unsigned int uid;
char *filename;
char *content;
};
char *initpath(void){
char filename[] = "Database.txt";
char *path = (char *)malloc(sizeof(char) * strlen(PATH) + 1);
if(path != NULL){
strcpy(path, PATH);
mkdir(path);
strcat(path, filename);
return path;
}
else
return NULL;
}
int initobj(struct user *elem, unsigned uid, char *username, char *password){
elem->uid = uid;
if((elem->username = (char *)malloc(sizeof(char) * strlen(username) + 1)) != NULL)
strcpy(elem->username, username);
else
return -1;
if((elem->password = (char *)malloc(sizeof(char) * strlen(password) + 1)) != NULL)
strcpy(elem->password, password); //Password is copied into the structure as a normal string. Future updata: encrypting the password
else
return -1;
return 0;
}
int insobj(int database, struct user elem){}
int checkid(int database, unsigned int id){}
int checkusr(int database, char *username){}
int checkpasw(int database, char *password){}
Here instead is the main function code:
#include <time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "database.h"
struct user playground;
int main(int argc, char *argv[]){
srand(time(0));
int err;
struct user *p = &playground;
char *filepath = initpath();
if(filepath != NULL && argc == 3){
if((err = initobj(p, (rand() % 999), argv[1], argv[2])) == 0)
printf("%u, %s, %s <- Data inserted.\n", p->uid, p->username, p->password);
else
printf("[DEBUG]: From function 'initobj' : %d.\n", err);
}
else
fprintf(stderr, "%s: Not enought arguments.\n", argv[0]);
}
The program keeps return me -1:
C:\Users\Computer\Desktop\ACCESS\Database\lib>dat username password
[DEBUG]: From function 'initobj' : -1.
Hence means malloc is not able to allocate space in head. I just don't understand why.
At least these issues:
Code fails to allocate sufficient space #
Johnny Mopp
char filename[] = "Database.txt";
char *path = (char *)malloc(sizeof(char) * strlen(PATH) + 1); // Wrong size & sense
if(path != NULL){
strcpy(path, PATH);
mkdir(path);
strcat(path, filename); // !! Undefined behavior (UB) !!
return path;
}
With the UB of strcat(path, filename);, rest of code is irrelevant.
Instead
Account for both PATH and filename
Cast not needed.
Scaling by sizeof(char) * strlen(PATH) + 1 should have been sizeof(char) * (strlen(PATH) + 1). sizeof(char) is 1 and is not needed either.
char filename[] = "Database.txt";
// PATH filename minus its \0 \0
char *path = malloc(strlen(PATH) + (sizeof filename - 1) + 1);
mkdir() may fail
Better code would test mkdir() success.
if (mkdir(path)) {
Handle_failure();
}

wcsrtombs returns (size_t) -1

I'm trying to figure out a way to convert from a string of type wchar_t* to char, but for some reason having trouble making it work. I have successfully done the opposite (from char to wchar_t*) with mbsrtowcs(), but this defeats me. The return value section inman 3 wcsrtombs has this:
The wcsrtombs() function returns the number of bytes that make up the
converted part of multibyte sequence, not including the terminating
null byte. If a wide character was encountered which could not be
converted, (size_t) -1 is returned, and errno set to EILSEQ.
Consider this minimal example:
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
char *convert_to_multibyte(const wchar_t* arg, long num_chars) {
size_t buffer_size = num_chars * sizeof(wchar_t);
char *mb = malloc(buffer_size); // will waste some memory though
mbstate_t state;
wcsrtombs(NULL, &arg, 0, &state); // this supposedly will initialize the mbstate_t struct
size_t result;
result = wcsrtombs(mb, &arg, buffer_size, &state);
if (result == (size_t)-1) {
free(mb);
return NULL;
}
mb[buffer_size-1] = '\0';
return mb;
}
int main(int argc, char* argv[]) {
setlocale(LC_ALL, "fi_FI.UTF-8");
wchar_t test[] = L"ÄÄÄÄÖÖÖÖ";
char *converted = convert_to_multibyte(test, wcslen(test));
// printf("%s\n", converted);
return 0;
}
With the test string L"ÄÄÄÄÖÖÖÖ", (size_t) -1 is returned, which implies an inconvertible wide char was encountered - this doesn't happen with a string that doesn't have any non-ASCII characters. What am I not understanding here?

How to write exact 1MB array in C?

I want to initialize an array of size 1MB. So my goal is finally write that 1MB to a file.
I am curious every time i use this formula it is giving less than 1mb.
int len = (1048576)/sizeof(int);
data = (int *) malloc(len);
What is correct way ?
Thank you
Edit - As per the comments I have changed the code .
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
int *data;
int bytes = (1024*1024);
data = (int *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (int)rand();
printf("%d",data[i]);
}
return 0;
}
After compiling it and I tried dumping the data like below
mpicc -o a mpiFileSize.c
./a > dump.dat
Now I see the file size of dump.dat. Why its 2.5MB ?
Try this
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *data;
int bytes = (1024*1024);
data = (char *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (char) rand();
printf("%c",data[i]);
}
return 0;
}
You shoul use character instead of integer.
Although it was already properly answered.
Just a plus to the answer, if one wants to choose the amount of MBs to allocate would make something like:
#include <malloc.h>
#define Mebabyte (1024 * 1024)
int main(int argc, char** argv)
{
void* data = malloc(2 * Megabyte);
// Do your work here...
free(data);
return 0;
}
If you wanted to allocate more than 2 MBs just change the 2.
As already stated before do not use integers as it's going to have more than 1 byte of size. Instead use char or unsigned char. And as stated by another post, there's no need to cast the result of malloc since void* can be turned to a pointer to any type (and in fact it's done implicitly by the compiler).
see: Why does this code segfault on 64-bit architecture but work fine on 32-bit?

Want to create a file with write mode in C

I am new in C. I want to create a file in linux C program and write environment variables in it. If file already exist I want to open and append. I have written the following code.
char *envFile=getenv("FILENAME");
int fdEnv=-1;
fdEnv=open(envFile,O_CREAT,O_RDWR,O_APPEND);
printf("%d",fdEnv);
char** env;
if(fdEnv>0)
{
for (env = environ; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s",thisEnv);
write(fdEnv,thisEnv,strlen(thisEnv));
}
close(fdEnv);
}
But when I run it first time. A blank file is created. And it stays locked after execution. Looks like some error. Second time it fdEnv stays less than 0.
I really don't understand what is happening here. Please help.
Try using | to separate the flags.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
extern char **environ;
int main(void)
{
char *envFile = getenv("FILENAME");
int fdEnv = -1;
fdEnv = open(envFile, O_CREAT|O_RDWR|O_APPEND, 0644);
printf("%d\n", fdEnv);
int i = 0;
while (environ[i]) {
printf("%s\n", environ[i]);
write(fdEnv, environ[i], strlen(environ[i]));
char lf = '\n';
write(fdEnv, &lf, 1);
i++;
}
close(fdEnv);
return 0;
}
I've run above code on my linux computer and it works.
extern char **environ;
int main()
{
char **env;
char* filename = getenv("FILENAME")
const char* mode = "a";
FILE* file = fopen( filename, mode );
for ( env = environ; *env; ++env )
fprintf( file, "%s\n", *env );
fclose(file);
return(0);
}
You should think about handling when getenv fails, is blank, etc; let me know if you have any questions.

c fwrite() writing to a file with only one of the struct variable?

This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. Right now the data only contains a.word, but it suppose to containst a.sorted too? I have check the a.sorted using printf
and it printf out the correct data, but why its not writing to the data file?
It still cant get the a.sorted even if i increase the count of the frwite
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#define SIZE 80
//struct
struct anagram {
char word[SIZE];
char sorted[SIZE];
};
void buildDB ( const char *const dbFilename ){
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL){
//get ripe of the '\n'
pos=strchr(word, '\n');
*pos = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j])
{
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
//printf(a);
fwrite(&a,1,strlen(word)+1,anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
it suppose to contains data with a.sorted for example "10th 01ht"
data:
fwrite(&a,1,strlen(word)+1,anagramsFile); should have been fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile); I assume the declaration of sorted as char sorted[SOME_LEN];

Resources