IDEA / CFB模式解密和损坏的块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IDEA / CFB模式解密和损坏的块相关的知识,希望对你有一定的参考价值。

我正在尝试理解OpenSSL库。我用C编写了一个程序,它应解密使用OpenSSL 1.1.0g加密的IDEA / CFB模式。这是到目前为止的代码:

#include <fcntl.h>                     /* O_RDONLY */
#include <stdio.h>                       /* printf */
#include <string.h>                      /* memcpy */
#include <unistd.h>                        /* read */
#include <openssl/idea.h>                  /* BF_* */
#include <openssl/evp.h>
#include <openssl/ripemd.h>

#define BUFFER_SIZE 861

unsigned char key[16];
unsigned char iv[8];

int read_file(char *file, unsigned char *buffer);

int main(void)
{

    unsigned char buffer[BUFFER_SIZE];
    unsigned char cipher_buffer[BUFFER_SIZE];
    unsigned char plain[BUFFER_SIZE];
    unsigned char iv_buffer[BUFFER_SIZE];
    unsigned char hash_buffer[BUFFER_SIZE];
    unsigned char final[BUFFER_SIZE];
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); 
    EVP_CIPHER *ciph;    
    char *cipher = "./cipher.bin";
    char *key1 = "./key.bin";

    //read key
    int blah = read_file(key1,buffer);
    printf("
Keylength: %d
", EVP_CIPHER_key_length(EVP_idea_cfb64()));
    printf("IV Length: %d
",EVP_CIPHER_iv_length(EVP_idea_cfb64()));
    printf("
KEY:");
    for(int i = 0;i<16;i++){
        key[i] = buffer[i];
        printf("%d ", buffer[i]);
    }

    printf("
IV : ");
    for(int i = 16;i<24;i++){
        iv[i] = buffer[i];
        printf("%d ", iv[i]);
    }

    //read cipher
    int cipherLen = read_file(cipher,cipher_buffer);
    unsigned char cipher_text[cipherLen];
    for(int i = 0; i<861;i++){
        cipher_text[i] = cipher_buffer[i];
    }

    int outlen = 0;  
    unsigned char lastl[BUFFER_SIZE];
    int last;
    EVP_CIPHER_CTX_init(ctx);
    EVP_CipherInit_ex(ctx,EVP_idea_cfb(),NULL,key,iv,0);
    EVP_CipherUpdate(ctx,plain,&last,cipher_buffer,BUFFER_SIZE);
    EVP_DecryptFinal_ex(ctx,plain,&last);

    printf("%s",plain);

    return 0;
}

int read_file(char *file, unsigned char *buffer){
    int fp = open(file,O_RDONLY);
    //printf("fd:%d File: %s
",fp,file);
    if(fp == -1){
        perror("File not found");
    }
    int f_size = lseek (fp , 0 , SEEK_END);
    lseek (fp , 0 ,SEEK_SET);
    printf("     f_size:%d
",f_size);
    read(fp,buffer,BUFFER_SIZE);

    //printf("lol:%d
", f_size);
    return f_size;
}

我遇到的问题是,当我打印结果时一切都很好,但文本的第一个块已损坏(前8个字节)我认为它与CFB模式有关,但我无法绕过头脑这个。 :(

这是输出:Output

这些是两个文件(cipher.bin和key.bin):

cipher.bin

key.bin

答案

在我身边犯了大错

我从文件中读出了密钥并搞砸了索引......

IV载体被破坏了

int j=0;
for(int i = 16;i<24;i++){
    iv[j] = buffer[i];
    printf("0x%02x,", iv[i]);
    j++;
}

修好了

以上是关于IDEA / CFB模式解密和损坏的块的主要内容,如果未能解决你的问题,请参考以下文章

AES/CFB8的高效解密

AES在线加密解密-附AES128,192,256,CBC,CFB,ECB,OFB,PCBC各种加密解密源码

分组密码的五种工作模式

Java加密,解密中的bc,cc是什么意思

python 实现AES加解密

python 实现AES加解密