【问题标题】:How to encrypt a message to Blowfish using OpenSSL?如何使用 OpenSSL 加密发送给 Blowfish 的消息?
【发布时间】:2017-02-08 01:08:53
【问题描述】:

我需要使用 OpenSSL 库进行 Blowfish 加密。但是有些东西不起作用。
我究竟做错了什么?我正在尝试这样做:

#include <iostream>
#include <openssl/blowfish.h>
#include "OpenSSL_Base64.h"
#include "Base64.h"

using namespace std;

int main()
{
    unsigned char ciphertext[BF_BLOCK];
    unsigned char plaintext[BF_BLOCK];

    // blowfish key
    const unsigned char *key = (const unsigned char*)"topsecret";
    //unsigned char key_data[10] = "topsecret";
    BF_KEY bfKey;
    BF_set_key(&bfKey, 10, key);

    /* Open SSL's Blowfish ECB encrypt/decrypt function only handles 8 bytes of data */
    char a_str[] = "8 Bytes";//{8, ,B,y,t,e,s,\0}
    char *arr_ptr = &a_str[0];

    //unsigned char* data_to_encrypt = (unsigned char*)"8 Bytes"; // 7 + \0

    BF_ecb_encrypt((unsigned char*)arr_ptr, ciphertext, &bfKey, BF_ENCRYPT);

    unsigned char* ret = new unsigned char[BF_BLOCK + 1];
    strcpy((char*)ret, (char*)ciphertext);
    ret[BF_BLOCK + 1] = '\0';

    char* base_enc = OpenSSL_Base64::Base64Encode((char*)ret, strlen((char*)ret));

    cout << base_enc << endl;

    cin.get();

    return 0;
}

但我得到了错误的输出:

fy7maf+FhmbM

我检查过:

http://sladex.org/blowfish.js/

应该是:fEcC5/EKDVY=

Base64:

http://pastebin.com/wNLZQxQT

【问题讨论】:

  • 这个问题已经被问过很多次了...openssl blowfish encryption example site:stackoverflow.comstrlen((char*)ciphertext 工作。另请参阅 OpenSSL wiki 上的 EVP Symmetric Encryption and Decryption。它甚至提供了一个使用它的 C++ 示例。
  • 没那么多。大部分问题我都看过了,在github上搜索了两天。我发现的都是不完整的,或者给出了错误的输出,所以我从头开始。我正在努力理解。
  • 当然Blowfish不应该用在新作品中,AES是目前的选择。
  • @zaph,为什么?河豚最快,我需要对移动网络游戏的流量进行加密。
  • @jww,好的,我稍微更改了代码,现在 {strlen} 必须工作。但是输出还是错了:fy7maf+FhmbM pastebin.com/u82UPwgV

标签: c++ encryption openssl blowfish


【解决方案1】:

问题在于ret 可能包含一个空字节,加密是基于 8 位字节的,而不是基于字符的,并且将包含 0-255 的整个范围内的值。 strlen 将在它找到的第一个空字节处终止,给出的长度小于加密数据的完整长度。

注意:使用加密时,请注意提供准确正确的长度参数和数据,不要依赖填充。 (例外情况是支持数据填充的加密函数的输入数据,例如 PKCS#7(née PKCS#5)填充。

【讨论】:

  • 密钥长度不正确(如果我手动设置为10(长度为10!),仅适用于strlen()。BF_set_key(&bfKey, strlen((char*)key), key); 如果消息是 8 字节加密错误,仅当超过 8 =\Сorrect 加密 + 几个垃圾字符(不是好像不是 \0)。我还是不明白 =\ 我明白了,我接受你的回答正确,我可能还有问题。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2011-01-10
  • 2019-08-15
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 2012-12-04
相关资源
最近更新 更多