/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void endecrypt(char *s1, char *s2, int l, int k)
{
    int i;
    srand(k);
    for(i = 0; i < l; i++)
    {
        s2[i] = s1[i] ^ (rand() % 256);
    }
    s2[l] = '\0';
}

int countesp(char *s, int l)
{
    int res,i;
    res = 0;
    for(i = 0; i < l; i++)
    {
        if(s[i] == 'e' || s[i] == ' ')
        {
            res++;
        }
    }
    return res;
}
int countrndst(char *s, int l)
{
    int res,i;
    res = 0;
    for(i = 0; i < l; i++)
    {
        if(s[i] == 'r' || s[i] == 'n' || s[i] == 'd' || s[i] == 's' || s[i] == 't')
        {
            res++;
        }
    }
    return res;
}
int analyze(char *s, int l)
{
    int k;
    char *buf;
    buf = (char *)malloc(l);
    k = 0;
    for(;;)
    {
        endecrypt(s, buf, l, k);
        if(countesp(buf, l) > l/5 && countrndst(buf, l) > 1/5)
        {
            free(buf);
            return k;
        }
        k++;
    }
}

int main()
{
    int l, k, k2;
    char p[200], c[200], p2[200], p3[200];
    printf("Enter key number: ");
    scanf("%d", &k);
    strcpy(p, "Dette er en lille test af hvor nemt det er at analysere en simpel RNG baseret kryptering");
    l = strlen(p);
    printf("%s\n", p);
    endecrypt(p, c, l, k);
    endecrypt(c, p2, l, k);
    printf("%s\n", p2);
    k2 = analyze(c, l);
    printf("key=%d\n", k2);
    endecrypt(c, p3, l, k2);
    printf("%s\n", p3);
    return 0;
}
