尝试加密并在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
程序成功加密,但是当我尝试显示密文时,它仅显示第一个字符。当我尝试在一个循环中按字符显示char时,它将所有字符显示为已加密。我检查了许多代码来修复它,但他们是通过这种方式完成的,而我无法修复。由于加密和解密功能可以正常工作,因此我没有附加它们,但是如果需要,我会附加。
已经感谢您的帮助。

最佳答案


您的加密文本(ciphertext)是一个二进制blob。它可能具有一些可打印的字符,例如A?或其他内容,但是还将具有一些不可打印的字符,例如ASCII值为1、2、3甚至0的字符。
考虑二进制二进制字符中的以下字符序列:

unsigned char data[] = {0x41, 0x00, 0x42, 0x43};
                     // 'A',  '\0', 'B',  'C'
data包含字符'A''\0'(空字节),'B''C'。如果尝试打印data,则只会看到A,因为下一个字符是空字节,遇到下一个字符将立即停止打印。
那么,如何显示二进制斑点?通常的方法是将二进制数据编码为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

关于c++ - 无法在Logcat上显示加密的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62675188/

10-11 23:16
查看更多