我在const_cast过程中出错
KeyPair.cpp: In member function ‘virtual bool KeyPairImpl::setKeyField(const std::string&, const std::string&)’:
KeyPair.cpp:188: error: invalid const_cast from type ‘const BIGNUM*’ to type ‘BIGNUM**’bool KeyPairImpl::setKeyField(const string &field, const string &value)
{
BIGNUM **f = const_cast<BIGNUM **>(getField(field));
if (!f)
return false;
// translate binary to bignum
*f = BN_bin2bn((const unsigned char *)&value[0], value.length(), *f);
return true;
}我相信这个问题发生在我改变了下面的职能之后。
const BIGNUM *KeyPairImpl::getField(const string &field) const
{
if (field == "P")
return DSA_get0_p(dsa_);
else if (field == "Q")
return DSA_get0_q(dsa_);
else if (field == "G")
return DSA_get0_g(dsa_);
else if (field == "X")
return DSA_get0_priv_key(dsa_);
else if (field == "Y")
return DSA_get0_pub_key(dsa_);
else
// unknown field name
return NULL;
}我在上述代码中所做的更改如下
Before: const BIGNUM * const *KeyPairImpl::getField(const string &field) const
After : const BIGNUM *KeyPairImpl::getField(const string &field) const请建议我如何正确地修改setKeyField方法。
发布于 2020-02-26 20:23:17
setKeyField()的实现都是错误的。
getField()返回一个const BIGNUM * (指向const BIGNUM的指针),但您正在尝试将其转换为指针到指针到BIGNUM的指针,这不是一回事。这就是编译器抱怨无效强制转换的原因。
您正在尝试为BN_bin2bn()提供一个指向BIGNUM的非空指针,以便将其写入。成功后,BN_bin2bn()将返回指向同一BIGNUM的指针,如果失败,则返回NULL。如果BN_bin2bn()失败(即输入value包含无效数据等),则不希望将NULL写回原始字段(无论如何都不能这样做)。因此,不要尝试将BN_bin2bn()的返回值赋值给f,它的ret参数将处理这个问题。仅将返回值用于错误处理。
此外,您没有考虑到value为空的可能性。访问空std::string的索引0是C++11之前的未定义行为。
试一试:
bool KeyPairImpl::setKeyField(const string &field, const string &value)
{
const BIGNUM *f = getField(field);
if (!f)
return false;
// translate binary to bignum
return BN_bin2bn(reinterpret_cast<const unsigned char *>(value.c_str()), value.length(), const_cast<BIGNUM*>(f));
/* alternatively, to avoid any possibility of corrupting
your field data if BN_bin2bn() happens to fail part-way
through its parsing...
BIGNUM *num = BN_bin2bn(reinterpret_cast<const unsigned char *>(value.c_str()), value.length(), NULL);
if (!num)
return false;
BN_copy(const_cast<BIGNUM*>(f), num);
BN_free(num);
return true;
*/
}我可能建议进一步声明并使用getField()的非const过载来处理该转换:
const BIGNUM* KeyPairImpl::getField(const string &field) const
{
if (field == "P")
return DSA_get0_p(dsa_);
else if (field == "Q")
return DSA_get0_q(dsa_);
else if (field == "G")
return DSA_get0_g(dsa_);
else if (field == "X")
return DSA_get0_priv_key(dsa_);
else if (field == "Y")
return DSA_get0_pub_key(dsa_);
else
// unknown field name
return NULL;
}
BIGNUM* KeyPairImpl::getField(const string &field)
{
const KeyPairImpl &cThis = *this;
return const_cast<BIGNUM*>(cThis.getField(field));
}
bool KeyPairImpl::setKeyField(const string &field, const string &value)
{
BIGNUM *f = getField(field);
if (!f)
return false;
// translate binary to bignum
return BN_bin2bn(..., f);
/* alternatively:
BIGNUM *num = BN_bin2bn(..., NULL);
...
BN_copy(f, num);
...
*/
}https://stackoverflow.com/questions/60421795
复制相似问题