【发布时间】:2019-03-20 12:35:34
【问题描述】:
请看下面的方法:
int BCVirtualCard::decrypt(std::string from, std::string *to, int keyId, bool padding)
{
if (to == nullptr)
{
NSCAssert(NO, @"Invalid params");
return 0;
}
NSString* privateKey = [m_storage privateKeyForSlot:keyId];
NSArray<NSString*>* components = [privateKey componentsSeparatedByString:@"_"];
const NSInteger componentsCount = 4;
if (components.count != componentsCount)
{
*to = "";
return 0;
}
const char* d = [components[0] UTF8String];
const char* n = [components[1] UTF8String];
const char* p = [components[2] UTF8String];
const char* q = [components[3] UTF8String];
RSA* rsa = RSA_new();
BN_hex2bn(&rsa->d, d);
BN_hex2bn(&rsa->n, n);
BN_hex2bn(&rsa->p, p);
BN_hex2bn(&rsa->q, q);
unsigned char* _to = (unsigned char *)calloc(1, sizeof(unsigned char));
int decryptedSize = RSA_private_decrypt((int)from.length(), (unsigned char *)from.c_str(), _to, rsa, RSA_NO_PADDING);
free(_to);
if (decryptedSize <= 0)
{
ERR_print_errors_cb(test, NULL);
*to = "";
return 0;
}
_to = (unsigned char *)calloc(decryptedSize, sizeof(unsigned char));
RSA_private_decrypt((int)from.length(), (unsigned char *)from.c_str(), _to, rsa, RSA_NO_PADDING);
*to = std::string((char *)_to, strlen((char *)_to));
free(_to);
RSA_free(rsa);
return 1;
}
这里的字符串from应该被解密并写入字符串to。对于解密,我使用RSA_private_decrypt 函数。我叫了两次。第一次是为了确定解密文本的大小,第二次是为了将解密的文本写入_to 缓冲区。当我第二次调用它时,它通常会像这样崩溃:
malloc: Heap corruption detected, free list is damaged at 0x280ff3d70
*** Incorrect guard value: 0
No1BCmail(2171,0x170efb000) malloc: *** set a breakpoint in malloc_error_break to debug
断点打开了,这让我找到了崩溃的地方。但是我无法理解它崩溃的原因。我第二次尝试重新创建RSA 结构并使用分配给_to 的大小,但没有任何帮助。你能看出这里有什么问题吗?谢谢
【问题讨论】:
-
_to实际上是空终止的吗?如果不是,您应该使用*to = std::string((char *)_to, decryptedSize); -
另外,根据this,您对解密的第一个调用是 UB:
to必须指向足够大的内存部分以保存解密数据(小于 RSA_size(rsa ))。 -
@NathanOliver 至于你的第二条评论——这就是我两次调用 RSA_private_decrypt 的全部原因。我根本不知道应该为 _to 缓冲区分配的大小。我需要先得到它。你看到了吗?
-
看起来使用
RSA_size(rsa)应该给你一个缓冲区大小来使用。它从rsa->n获取该值。所以你可以做unsigned char* _to = new unsigned char[RSA_size(rsa)]; ...; delete _to。 -
@NathanOliver 我不太擅长 RSA。你的意思是解密文本的大小总是小于或等于n?对吗?
标签: c++ objective-c openssl rsa objective-c++