【问题标题】:can't show the encrypted text on Logcat无法在 Logcat 上显示加密文本
【发布时间】:2020-07-01 10:52:05
【问题描述】:

主函数尝试加密并在 logcat 上显示

aes = new ofxLibcrypto();
// start
unsigned char *key = (unsigned char *)"qwertyuiqwertyuiqwertyuiqwertyui";
unsigned char *iv = (unsigned char *)"qwertyuiqwertyui";
unsigned char *plaintext = (unsigned char *)"The quick brown fox jumps over the lazy dog";
unsigned char *ciphertext;
unsigned char decryptedtext[128];
int ciphertext_len, decryptedtext_len;
ciphertext_len = aes->encrypt(plaintext, strlen((char*)plaintext), key, iv, ciphertext);


ofLogNotice("IDB") << "Encrpyted: " << ciphertext;


decryptedtext_len = aes->decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
decryptedtext[decryptedtext_len] = (unsigned char) "\0";
ofLogNotice("IDB") << "Decrypted: " << decryptedtext;
// end

程序加密成功,但是当我尝试显示密文时,它只显示第一个字符。当我尝试在循环中按字符显示字符时,它会将所有字符显示为加密。我检查了许多代码来修复它,但他们这样做了,我无法修复它。由于加密和解密功能工作正常,我没有附上它们,但如果需要我会附上。

已经感谢谁会提供帮助。

【问题讨论】:

  • 加密是创建一个以 null 结尾的字符串,还是生成二进制 blob?如果它是二进制 blob,则不能将其用作以 null 结尾的字符串并按原样显示。
  • 您不能仅通过打印来显示加密文本。通常通过将二进制数据转换为十六进制来显示。

标签: c++ encryption openssl aes


【解决方案1】:

无法显示加密文本

您的加密文本 (ciphertext) 是二进制 blob。它可能有一些可打印的字符,例如A? 或其他东西,但也会有一些不可打印的字符,例如 ASCII 值为 1、2、3 甚至 0 的字符。

考虑二进制 blob 中的这个字符序列:

unsigned char data[] = {0x41, 0x00, 0x42, 0x43};
                     // 'A',  '\0', 'B',  'C'

data 包含字符 'A''\0'(空字节)、'B''C'。如果你尝试打印data,你只会看到A,因为下一个字符是空字节,遇到它会立即停止打印。

那么,如何显示二进制 blob?通常的做法是将二进制数据编码为base16 或其他基数。

这是一个用 base16 对数据进行编码的简单函数:

template <typename T>
std::string toBase16(const T itbegin, const T itend)
{
    std::string rv;
    static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    rv.reserve(std::distance(itbegin, itend) * 2);
    for (T it = itbegin; it < itend; ++it) {
        unsigned char val = (unsigned char)(*it);
        rv.push_back(hexmap[val >> 4]);
        rv.push_back(hexmap[val & 15]);
    }
    return rv;
}

用法:

int ciphertext_len, decryptedtext_len;
ciphertext_len = aes->encrypt(plaintext, strlen((char*)plaintext), key, iv, ciphertext);

ofLogNotice("IDB") << "Encrpyted: " << toBase16(ciphertext, ciphertext + ciphertext_len);

另一种方法是将每个字节转换为int,然后显示其十进制值:

unsigned char data[] = {0x41, 0x00, 0x42, 0x43};
                     // 'A',  '\0', 'B',  'C'
for (int i = 0; i < 4; ++i)
{
    cout << static_cast<int>(data[i]) << ' ';
}
//Output: 65 0 66 67

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多