无法在 Logcat 上显示加密文本

can't show the encrypted text on Logcat

尝试加密并在 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) "[=11=]";
ofLogNotice("IDB") << "Decrypted: " << decryptedtext;
// end

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

已经感谢谁会提供帮助。

can't show the encrypted text

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

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

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

data包含字符'A''[=19=]'(空字节)、'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',  '[=13=]', 'B',  'C'
for (int i = 0; i < 4; ++i)
{
    cout << static_cast<int>(data[i]) << ' ';
}
//Output: 65 0 66 67