Consolidate Bignum2ByteArray conversion implementations

Unify the different implementations of Bignum-to-QByteArray
implementations by our BioByteArray class.

Also support alignment to a minimal bitsize.
This commit is contained in:
Christian Hohnstaedt 2024-09-11 00:08:37 +02:00
parent a3dd931fb3
commit 7078853573
4 changed files with 25 additions and 24 deletions

View File

@ -6,8 +6,24 @@
*/
#include "BioByteArray.h"
#include "func_base.h"
#include <QDebug>
BioByteArray::BioByteArray(const BIGNUM *bn, int bits)
{
int len = (bits+7) >> 3;
qDebug() << bits << len;
if (!bn)
return;
store.resize(BN_num_bytes(bn));
BN_bn2bin(bn, (unsigned char *)store.data());
openssl_error();
if (store.size() > 0 && (char)store[0] < 0)
store.prepend('\0');
if (len > 0 && store.size() < len)
store.prepend(len - store.size(), 0);
}
void BioByteArray::set(const QByteArray &qba)
{
if (read_write) {

View File

@ -11,6 +11,7 @@
#include <QByteArray>
#include <QString>
#include <openssl/bio.h>
#include <openssl/bn.h>
class BioByteArray
{
@ -27,6 +28,7 @@ class BioByteArray
public:
BioByteArray(const QByteArray &qba) : store(qba) { }
BioByteArray(const BioByteArray &bba) : store(bba.byteArray()) { }
BioByteArray(const BIGNUM *bn, int len = 0);
BioByteArray() { }
~BioByteArray();
int size() const;

View File

@ -66,7 +66,8 @@ macro(Test name)
endmacro()
if(BUILD_TESTING)
Test(test_biobytearray BioByteArray.cpp BioByteArray.h)
Test(test_biobytearray BioByteArray.cpp BioByteArray.h
func_base.cpp func_base.h)
Test(test_asn1int asn1int.cpp asn1int.h func_base.h func_base.cpp)
Test(test_asn1time asn1time.cpp asn1time.h func_base.h func_base.cpp)
Test(test_entropy entropy.cpp entropy.h func.h func_base.cpp xfile.h)

View File

@ -382,22 +382,10 @@ void pki_key::writePublic(XFile &file, bool pem) const
QString pki_key::BN2QString(const BIGNUM *bn) const
{
if (bn == NULL)
return "--";
QString x="";
char zs[10];
int j, size = BN_num_bytes(bn);
unsigned char *buf = (unsigned char *)OPENSSL_malloc(size);
Q_CHECK_PTR(buf);
BN_bn2bin(bn, buf);
for (j = 0; j< size; j++) {
snprintf(zs, sizeof zs, "%02X%c",buf[j], ((j+1)%16 == 0) ? '\n' :
j<size-1 ? ':' : ' ');
x += zs;
}
OPENSSL_free(buf);
pki_openssl_error();
return x;
QByteArray hex, ba = BioByteArray(bn);
for(int i = 0; i<ba.size(); i += 16)
hex += ba.mid(i, 16).toHex(':') + '\n';
return QString::fromLatin1(hex);
}
QVariant pki_key::column_data(const dbheader *hd) const
@ -638,13 +626,7 @@ void pki_key::ssh_key_QBA2data(const QByteArray &ba, QByteArray *data) const
void pki_key::ssh_key_bn2data(const BIGNUM *bn, QByteArray *data) const
{
QByteArray big;
big.resize(BN_num_bytes(bn));
BN_bn2bin(bn, (unsigned char *)big.data());
pki_openssl_error();
if ((unsigned char)big[0] >= 0x80)
big.prepend('\0');
ssh_key_QBA2data(big, data);
ssh_key_QBA2data(BioByteArray(bn), data);
}
bool pki_key::SSH2_compatible() const