HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Cryptoanalysis of Vigenere-ciphered text with Kasiski test

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
kasiskiwithcryptoanalysistextvigeneretestciphered

Problem

I am creating a program that will analyse encrypted text using Kasiski examination in order to find possible key length:

#include 
#include 
#include 
#include 
#include 

char *file_get_contents(char *filename, char *fmode) {
    FILE *f = fopen(filename, fmode);
    fseek(f, 0L, SEEK_END);
    long fsize = ftell(f);
    rewind(f);
    char *file_contents = malloc(fsize+1);
    fread(file_contents, fsize, 1, f);
    fclose(f);
    file_contents[fsize] = 0;
    return file_contents;
}

char *str_copy(char *string, int start, int length) {
    char *s = malloc(length);
    strncpy(s, string+start, length);
    s[length+1] = '\0';    
    return s;
}

void count_factors(int *array, int number) {
    int i;
    for (i=2; i 1)
            printf("%d: %d \n", i, factors_value[i]);
    }

    printf("%llu iterations\n", iterations);

    free(file_contents);
    free(factors_value);

    end = clock();
    cpu_time_used = ((double) (end-start)) / CLOCKS_PER_SEC;
    printf("Process finished: %4.3f secs.\n", cpu_time_used);
    getch();
    return 0;
}


I've done all my best in order to make this process be as fast as I could make it, however, I consider this code pretty slow. Using test text with length = 25663 characters I get the following results:

  • 251,375,553 iterations



  • processing time: 17,387 seconds.



The text for this test (originally taken from dummytext-generator website) was encrypted with a key that is 5 characters long. As a final result I get the following top of possible key values (value: number of occurrences):

2: 28227
 3: 17769
 4: 14605
 5: 50093
10: 25452
15: 15880
20: 13169


The result is pretty precise in my opinion.

So, my question is: how can I increase the performance of this code?

Solution

Fatal: Insufficient memory allocation. Buffer is too small by 2 for s[length+1].

char *s = malloc(length);
...
s[length+1] = '\0';


Minor: long will not necessarily will fit in size_t.

long fsize = ftell(f);
...
char *file_contents = malloc(fsize+1);


Wrong specifier. I'd expect a good compiler with properly enabled warnings would flag this.

unsigned long iterations = 0;
...
printf("%llu iterations\n", iterations);


Suggest checking code for correctness and re-submit.

Code Snippets

char *s = malloc(length);
...
s[length+1] = '\0';
long fsize = ftell(f);
...
char *file_contents = malloc(fsize+1);
unsigned long iterations = 0;
...
printf("%llu iterations\n", iterations);

Context

StackExchange Code Review Q#104756, answer score: 6

Revisions (0)

No revisions yet.