首页 > 解决方案 > 解密 Vernam 密码

问题描述

我正在为 Vernam Cipher 创建加密和解密代码。

最初,要加密消息,我必须使用一个可以生成 OTP 的函数。该函数产生 1-26 的随机数(表示英文字母),并将存储在整数数组中。大小等于要加密的消息的长度。

我能够做到这一点。我的问题是如何解密它。

我有这个代码。

我的 OTP 数组,因为每个元素在 1-26 之间随机排列,所以表示字母表中的第 n 个字母。例如 25 表示字母 'y' 等等。 我的加密逻辑是,由于我的 OTP 数组的大小等于我的消息的长度,我将对我的消息的每个字符和我的 OTP 进行 XOR。这是在根据每个元素的随机分配编号将我的 OTP 数组转换为相应的字母之后。我已经能够进行加密部分了。但是每当我尝试解密时,我都会收到与我最初输入的不同的消息。

void encryptiondecryption(char msg[], char key[]){
    
    int i,j=0,x,m=0;

    char output[100];
    char output2[100];

/* Loop to remove all spaces in the message here*/  

/*Encryption*/    
    int modd;
    for(x = 0; msg[x]!='\0'; x++) {
    printf("\nletter:%c - key:%c",msg[x], key[x] );
        modd = (msg[x] ^ key[x]);
        if(modd == 26){
            output[x] = 'a'+ (modd%26)+25;
        }else{
            output[x] = 'a'+ (modd%26)-1;
        }
    }
    output[x]='\0';

    printf("\nEncrypted Message:\n");
    for(x = 0; output[x]!='\0'; x++) {
        printf("%c",output[x]);
    }

/* decryption */

    int modd2,diff,sum, toXOR;
    printf("\n\ndecryption\n");

    for(x = 0; output[x]!='\0'; x++) {
        printf("\nletter:%c - key:%c",output[x], key[x] );
        diff = output[x] - 'a';
        if(diff == 25){
            sum = diff - 25;
            toXOR = sum + 26;
            output2[x] = toXOR ^ key[x];
        }else{
            sum = diff + 1;
            toXOR = sum + 26;
            output2[x] = toXOR ^ key[x];
        }

    }

    output2[x]='\0';
    printf("\n Output for Decryption\n");
        for(i = 0;  output2[i]!='\0'; i++) {
        printf("%c",output2[i]);
    }
}

另外,这是我的 generateOTP 函数。

char* generateKey(char msg[]){
    srand(time(NULL)); 
    int len = strlen(msg);
    

    int numbers[len];
    int x,y=0, m=0,a;
    
    for(x=0;x<len;x++){
        if(msg[x]!='_') m++;
    }

    
    printf("generated key is . . .\n");
    int *getOTP = malloc (sizeof (int)*len);
    
    for(x=0;x<m;x++){
        getOTP[x] = rand() % (26 - 1 + 1) + 1;
    }
    for(x=0;x<m;x++){
        printf("%d ", getOTP[x]);
    }
    
    char *letterOTP = malloc (sizeof (char) * len);
    int getOTP2[m];
    for(x=0;x<m;x++){
        getOTP2[x] = getOTP[x];
    }

    int md;
    for(x=0;x<m;x++){
        md = (getOTP2[x]) % 26;
        if(md ==0){
            letterOTP[x] =( 97 + (md));
        }else{
            letterOTP[x] =( 97 + (md) - 1);
        }
        
    }
    letterOTP[x] = '\0';

    return letterOTP;
    
}

基本上,正如我上面提到的那样,它的作用是根据数组中的元素被随机分配的数字来分配字母(e.g. 25 = 'y', 5 = 'e')

标签: c

解决方案


推荐阅读