0

Not sure why but the key that get generated using the *randstring function has inaudible computer language symbols like triangle with ? inside of it, and I can't use the key to decrypt because it says invalid key.

Also how can I clear the screen therefore the key to no longer appear in the terminal?

https://i.stack.imgur.com/EJ7y9.jpg

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *randstring(size_t length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";        
    char *randomString = NULL;

    if (length) {
        randomString = malloc(sizeof(char) * (length +1));

        if (randomString) {            
            for (int n = 0;n < length;n++) {            
                int key = rand() % (int)(sizeof(charset) -1);
                randomString[n] = charset[key];
            }

            randomString[length] = '\0';
        }
    }

    return randomString;
}

int main()
{
    int tempint = 20;
    char *newchar = randstring(tempint);
    char private_key[20];
    strcpy(newchar, private_key);
    char check_for_privatekey[20];
    char text_to_encrypt[20];


    printf("Enter text to encrypt: ");
    if (fgets(text_to_encrypt, 20, stdin) == NULL) {
        printf("Input error.\n");
        exit(1);
    }

    // START PROCCESS
    printf("Encrypting string->%s\n", text_to_encrypt);
    puts("This is where private_key is assigned");
    printf("Your private key is:%s\n", private_key);
    // "Encrypted with private key"

    while(1)
    {
    printf("Enter private key: \n");
     if (fgets(check_for_privatekey, 20, stdin) == NULL) {
        printf("Input error.\n");
        exit(1);
    }


    if (strncmp(check_for_privatekey, private_key, 3) == 0)
    {
        printf("String decrypted\n ##%s", text_to_encrypt);
    }


    else
    {
        printf("Invalid key\n");
    }
    
    
    }
    

    return 0;
}
  • `char private_key[20]` isn't big enough, it needs to be `char private_key[21]` to allow room for the null terminator. – Barmar Jun 20 '22 at 20:35
  • 1
    Shouldn't `strcpy(newchar, private_key);` be `strcpy(private_key, newchar);`? Otherwise I don't see where you ever fill in `private_key`. – kaylum Jun 20 '22 at 20:37
  • Why do you think you need the `private_key` variable? You can just use `newchar`. – Barmar Jun 20 '22 at 20:37
  • Don't forget that `fgets()` leaves the newline in the string if there's room for it. See https://stackoverflow.com/questions/13443793/fgets-includes-the-newline-at-the-end for how to remove it before comparing with other strings. – Barmar Jun 20 '22 at 20:38

0 Answers0