【问题标题】:QString to const byte* conversionQString 到 const byte* 的转换
【发布时间】:2012-10-02 19:39:17
【问题描述】:

我正在尝试使用 Botan 库创建几个 QStrings 的 SHA-256 哈希 - 一个密码和一个盐。我做了很多尝试,试图将连接的盐+密码转换为正确的类型,以便输入到 Botan 进程函数中。我试图在 Botan 中使用的类的文档位于 botan sha-256 documentation 我最近的尝试是

///
/// Computes salted data hash
///

QByteArray MyClass::HashData(QString salt, QString password)
{
    QString concatenated = salt+password;
    QByteArray input(concatenated.toLocal8Bit());
    Botan::SHA_256 sha;
    Botan::SecureVector<Botan::byte> saltedHash
            = sha.process(&input,input.count()-1);  // -1 to get rid of the \0
    return QByteArray(saltedHash);
}

编译时出现错误:没有调用'Botan::SHA_256::process(QByteArray*, int)'的匹配函数...候选者是:/usr/include/botan-1.10/botan/buf_comp .h:101: Botan::SecureVector Botan::Buffered_Computation::process(const byte*, size_t)

如何将 QString 或 QByteArray 转换或复制到 const byte* 中?

编辑:发布问题后,我尝试了更多方法。下面附上了一个似乎可行的方法,但我对使用 reinterpret_cast 感到不舒服,因为它看起来可能会导致我在我的 c++ noob 状态下不知道的问题。

Botan::SecureVector<Botan::byte>  MyClass::HashData(QString salt, QString password)
{
    QString concatenated = salt+password;
    QByteArray buffer(concatenated.toLocal8Bit());
    unsigned char * input = reinterpret_cast< unsigned char*>(buffer.data());

    Botan::SHA_256 sha;
    Botan::SecureVector<Botan::byte> saltedHash
            = sha.process(input,buffer.count()-1);  // -1 to get rid of the \0
    return (saltedHash);
}

【问题讨论】:

  • 你的转换应该没问题,因为 buffer.data() 返回 char* 来表示字符(不能是负值)。在这种情况下,plain char 和 unsigned char 是相同的。 stackoverflow.com/questions/2054939/…

标签: c++ qt botan


【解决方案1】:

有同样的问题:QByteArray convert to/from unsigned char *

但是你为什么不使用reinterpret_cast,例如这样:

...
QString salt = "salt";
QString password = "password";
QString concatenated = QString("%1%2").arg(salt).arg(password);
unsigned char * input = (unsigned char *) concatenated. toLocal8Bit().data();
printf("%s", input);
...

【讨论】:

  • 我读过很多文章,建议 c++ reinterpret cast 优于 c-type cast。
【解决方案2】:

您可以使用以下方法。

const char * QByteArray::data()

【讨论】:

  • 如果我用const unsigned char * input = const unsigned char * buffer::data(); 替换该行,编译器会返回错误'conflicting declaration 'const unsigned char* input'。 (请注意,需要一个无符号字符。)
猜你喜欢
  • 2014-12-11
  • 1970-01-01
  • 2020-11-13
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多