B中的Blowfish加密和解密

时间:2013-09-02 15:52:16

标签: c algorithm blowfish

所以这是我的C程序,我无法弄清楚为什么我无法解密加密的字符串。我想写一个小的C程序,它接受一个字符串,加密,然后获取加密的字符串和提供的密钥,解密。两个问题: A)我在这里做错了什么? B)密钥是如何存储的,也就是说,如果我现在正在进行新的加密并且用户想要解密之前的文本,那么当他提供密码时,blowfish会知道如何解密它吗?

以下是河豚的文档: http://www.openssl.org/docs/crypto/blowfish.html 现在我的计划:

#include <string.h>
#include "blowfish.h"
#include "bf_pi.h"
#include "bf_locl.h"
#include <stdio.h>
#include <stdlib.h>

int main()
 {
    char from[128], to[128];
    int len = 128;
    BF_KEY key;
    char temp_buf[16];
    int n = 0;          /* internal blowfish variables */
    unsigned char iv[8];        /* Initialization Vector */
    /* fill the IV with zeros (or any other fixed data) */
    memset(iv, 0, 8);


    printf("input password: ");
    scanf("%s", &temp_buf);

    strcpy(from, "ABCDEFGHTHISISTHEDATA"); //ENCRYPT THIS

    BF_set_key(&key, 16, temp_buf);

    BF_cfb64_encrypt(from, to, len, &key, iv, &n, BF_ENCRYPT);
    printf("encrypted to -->  %s\n", to); //SUCCESSFULY ENCRYPTED


    BF_cfb64_encrypt(from, to, len, &key, iv, &n, BF_DECRYPT);
    printf("File %s has been decrypted to --> %s \n",from,  to); //FAILS DOES NOT DECRYPT
}

1 个答案:

答案 0 :(得分:1)

我认为您应该切换fromto变量:

//as WhozCraig mentioned, fill in n and iv again before decryption
n = 0;          /* internal blowfish variables */
/* fill the IV with zeros (or any other fixed data) */
memset(iv, 0, 8);

BF_cfb64_encrypt(to, from, len, &key, iv, &n, BF_DECRYPT);
printf("File %s has been decrypted to --> %s \n",to,  from); //FAILS DOES NOT DECRYPT
  

保留原来的IV(这并不难;   它全部为零)并在解密之前将n重置为零   得到OP想要的东西 - WhozCraig