...
 
Commits (11)
*.pro.user
*.pro.user*
/builds/
/Qt-Secret/src/build/
/Qt-Secret/src/mini-gmp/src/build/
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
//#
//# Copyright (C) 2018-2019 QuasarApp.
//# Distributed under the lgplv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#include "qrsaencryption.h"
#include <QString>
#include <iostream>
#include <ctime>
#include <chrono>
#define KEY_GEN_LIMIT 10
const QString SIGN_MARKER = "-SIGN-";
const int signMarkerLength = SIGN_MARKER.length();
QRSAEncryption::INT eulerFunc(const QRSAEncryption::INT &p, const QRSAEncryption::INT &q) {
return (p - 1) * (q - 1);
}
bool QRSAEncryption::isMutuallyPrime(const INT &a, const INT &b) {
if ( (!(a % 2) && !(b % 2))
|| (!(a % 3) && !(b % 3))
|| (!(a % 5) && !(b % 5))
|| (!(a % 7) && !(b % 7))
) return false;
return INT().gcd(a, b) == 1;
}
QRSAEncryption::Rsa QRSAEncryption::getBitsSize(const INT &i) const {
int rsaBits = RSA_64;
int intBits = i.sizeBits();
while (rsaBits < intBits) {
rsaBits *= 2;
}
return static_cast<QRSAEncryption::Rsa>(rsaBits);
}
QRSAEncryption::Rsa QRSAEncryption::getBitsSize(const QByteArray &key) const {
if (isValidRsaKey(key)) {
return static_cast<QRSAEncryption::Rsa>(key.size() * 4);
}
return QRSAEncryption::Rsa::Invalid;
}
QRSAEncryption::INT QRSAEncryption::fromArray(const QByteArray &array) const {
INT res = 0;
res.fromHex(array.toHex().toStdString());
return res;
}
QByteArray QRSAEncryption::toArray(const INT &i, short sizeBlok) {
QByteArray res;
res = QByteArray::fromHex(QByteArray::fromStdString(i.getString(16)));
if (sizeBlok < 0) {
return res;
}
while (res.size() < sizeBlok) {
res.push_front(char(0));
}
return res.left(sizeBlok);
}
QRSAEncryption::INT QRSAEncryption::randomNumber(bool fullFill) const {
srand(std::chrono::duration_cast<std::chrono::nanoseconds>
(std::chrono::system_clock::now().time_since_epoch()).count()
% std::numeric_limits<int>::max());
INT res{1};
if(fullFill) {
while(res.longBits() < _rsa) {
res *= (rand() % (std::numeric_limits<int>::max() - 1)) + 1;
}
} else {
int longDiff = _rsa / (sizeof (int) * 8);
while (longDiff > 0) {
longDiff--;
res *= (rand() % (std::numeric_limits<int>::max() - 1)) + 1;
}
}
return res;
}
QRSAEncryption::INT QRSAEncryption::toPrime(INT n) const {
if (!(n % 2)) {
++n;
}
INT LN = n;
INT RN = n;
while (true) {
if (LN.isPrime(false)) return LN;
RN+=2;
if (RN.isPrime(false)) return RN;
LN-=2;
}
}
QRSAEncryption::INT QRSAEncryption::randomPrimeNumber(INT no) const {
srand(static_cast<unsigned int>(time(nullptr)));
// max INT
INT max('1', _rsa / 2, 2);
auto p = toPrime(randomNumber() % max);
while(p == no) p = toPrime(randomNumber() % max);
return p;
}
QRSAEncryption::INT QRSAEncryption::extEuclid(INT a, INT b) const {
INT x = 0, y = 1, u = 1, v = 0, gcd = b, m, n, q, r;
while (a != 0) {
q = gcd / a;
r = gcd % a;
m = x - u * q;
n = y - v * q;
gcd = a;
a = r;
x = u;
y = v;
u = m;
v = n;
}
return y;
}
short QRSAEncryption::getBlockSize(INT i) const {
return static_cast<short>(i.longBytes()) - 1;
}
QByteArray QRSAEncryption::encodeBlok(const INT &block, const INT &e, const INT &m, short blockSize) {
return toArray(INT::powm(block, e, m), blockSize);
}
QByteArray QRSAEncryption::decodeBlok(const INT &block, const INT &d, const INT &m, short blockSize) {
return toArray(INT::powm(block, d, m), blockSize);
}
QRSAEncryption::QRSAEncryption(Rsa rsa) {
_rsa = rsa;
}
bool QRSAEncryption::generatePairKeyS(QByteArray &pubKey, QByteArray &privKey, QRSAEncryption::Rsa rsa) {
qWarning() << "method " << Q_FUNC_INFO <<
" will be deleted in newxt version. please use generatePairKey method";
return generatePairKey(pubKey, privKey, rsa);
}
QByteArray QRSAEncryption::encodeS(const QByteArray &rawData, const QByteArray &pubKey, QRSAEncryption::Rsa rsa, QRSAEncryption::BlockSize blockSizeMode) {
qWarning() << "method " << Q_FUNC_INFO <<
" will be deleted in newxt version. please use encode method";
return encode(rawData, pubKey, rsa, blockSizeMode);
}
QByteArray QRSAEncryption::decodeS(const QByteArray &rawData, const QByteArray &privKey, QRSAEncryption::Rsa rsa, QRSAEncryption::BlockSize blockSizeMode) {
qWarning() << "method " << Q_FUNC_INFO <<
" will be deleted in newxt version. please use decode method";
return decode(rawData, privKey, rsa, blockSizeMode);
}
QByteArray QRSAEncryption::signMessageS(QByteArray rawData, const QByteArray &privKey, QRSAEncryption::Rsa rsa) {
qWarning() << "method " << Q_FUNC_INFO <<
" will be deleted in newxt version. please use signMessage method";
return signMessage(rawData, privKey, rsa);
}
bool QRSAEncryption::checkSignMessageS(const QByteArray &rawData, const QByteArray &pubKey, QRSAEncryption::Rsa rsa) {
qWarning() << "method " << Q_FUNC_INFO <<
" will be deleted in newxt version. please use signMessage method";
return checkSignMessage(rawData, pubKey, rsa);
}
unsigned int QRSAEncryption::getKeyBytesSize(QRSAEncryption::Rsa rsa) {
return rsa / 4;
}
// --- static methods ---
bool QRSAEncryption::generatePairKey(QByteArray &pubKey, QByteArray &privKey,
QRSAEncryption::Rsa rsa) {
return QRSAEncryption(rsa).generatePairKey(pubKey, privKey);
}
QByteArray QRSAEncryption::encode(const QByteArray &rawData, const QByteArray &pubKey,
Rsa rsa, BlockSize blockSizeMode) {
return QRSAEncryption(rsa).encode(rawData, pubKey, blockSizeMode);
}
QByteArray QRSAEncryption::decode(const QByteArray &rawData, const QByteArray &privKey,
Rsa rsa, BlockSize blockSizeMode) {
return QRSAEncryption(rsa).decode(rawData, privKey, blockSizeMode);
}
QByteArray QRSAEncryption::signMessage(QByteArray rawData, const QByteArray &privKey, Rsa rsa) {
return QRSAEncryption(rsa).signMessage(rawData, privKey);
}
bool QRSAEncryption::checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey, Rsa rsa) {
return QRSAEncryption(rsa).checkSignMessage(rawData, pubKey);
}
// --- end of static methods ---
bool QRSAEncryption::generatePairKey(QByteArray &pubKey, QByteArray &privKey) {
int cnt{0};
bool keyGenRes{false};
INT p, q, modul, eilor, e, d;
do {
pubKey.clear();
privKey.clear();
p = randomPrimeNumber();
q = randomPrimeNumber(p);
modul = 0;
while ((modul = p * q) < 0) {
p = toPrime((p - 1) / 2);
}
eilor = eulerFunc(p, q);
e = randomNumber() % eilor;
if (!(e % 2)) --e;
do {
e -= 2;
} while((!isMutuallyPrime(eilor, e)));
d = extEuclid(eilor , e);
while(d < 0 ) {
d += eilor;
}
pubKey.append(toArray(e, _rsa / 8));
pubKey.append(toArray(modul, _rsa / 8));
privKey.append(toArray(d, _rsa / 8));
privKey.append(toArray(modul, _rsa / 8));
} while (!(keyGenRes = testKeyPair(pubKey, privKey)) && (++cnt < KEY_GEN_LIMIT));
if(cnt >= KEY_GEN_LIMIT) qWarning() << QString("(Warning): Exceeded limit of key generation (%0)!").arg(KEY_GEN_LIMIT);
return (keyGenRes && cnt < KEY_GEN_LIMIT);
}
// --- non-static methods ---
QByteArray QRSAEncryption::encode(const QByteArray &rawData, const QByteArray &pubKey, BlockSize blockSizeMode) {
if (getBitsSize(pubKey) != _rsa) {
return QByteArray();
}
int index = 0;
QByteArray block;
INT e = fromArray(pubKey.mid(0, pubKey.size() / 2));
INT m = fromArray(pubKey.mid(pubKey.size() / 2));
short blockSizeOut = getBlockSize(m) + 1; // BlockSize::OneByte
short blockSizeIn = 1; // BlockSize::OneByte
if (blockSizeMode == BlockSize::Auto) {
blockSizeIn = getBlockSize(m);
}
if (!blockSizeIn) {
qDebug() << "module of key small! size = 1 byte, 2 byte is minimum";
return QByteArray();
}
QByteArray res;
while ((block = rawData.mid(index, blockSizeIn)).size()) {
if (index + blockSizeIn > rawData.size() && block.size() && !block[0]) {
qWarning() << "When trying to encrypt data, problems arose, the last block contains non-significant zeros."
" These zeros will be deleted during the decryption process."
" For encode and decode data with non-significant zeros use BlockSize::OneByte";
}
res.append(encodeBlok(fromArray(block), e, m, blockSizeOut));
index += blockSizeIn;
}
return res;
}
QByteArray QRSAEncryption::decode(const QByteArray &rawData, const QByteArray &privKey, BlockSize blockSizeMode) {
if (getBitsSize(privKey) != _rsa) {
return QByteArray();
}
int index = 0;
QByteArray block;
INT d = fromArray(privKey.mid(0, privKey.size() / 2));
INT m = fromArray(privKey.mid(privKey.size() / 2));
short blockSizeIn = getBlockSize(m) + 1;
short blockSizeOut = 1; // BlockSize::OneByte
if (blockSizeMode == BlockSize::Auto) {
blockSizeOut = getBlockSize(m);
}
QByteArray res;
while ((block = rawData.mid(index, blockSizeIn)).size()) {
bool isLastBlock = (index + blockSizeIn) >= rawData.size();
res.append(decodeBlok(fromArray(block), d, m,
(isLastBlock && blockSizeMode == BlockSize::Auto)? -1 : blockSizeOut));
index += blockSizeIn;
}
return res;
}
QByteArray QRSAEncryption::signMessage(QByteArray rawData, const QByteArray &privKey) {
QByteArray hash = QCryptographicHash::hash(rawData, HashAlgorithm::Sha256);
QByteArray signature = encode(hash, privKey, BlockSize::OneByte);
rawData.append(SIGN_MARKER + signature.toHex() + SIGN_MARKER);
return rawData;
}
bool QRSAEncryption::checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey) {
// start position of SIGN_MARKER in rawData
auto signStartPos = rawData.lastIndexOf(SIGN_MARKER, rawData.length() - signMarkerLength - 1);
// length of signature in rawData
auto signLength = rawData.length() - signStartPos - signMarkerLength * 2;
// message, that was recieved from channel
QByteArray message = rawData.left(signStartPos);
// hash, that was decrypt from recieved signature
QByteArray recievedHash = decode(QByteArray::fromHex(rawData.mid(signStartPos + signMarkerLength, signLength)),
pubKey, BlockSize::OneByte);
// if recievedHash == hashAlgorithm(recived message), then signed message is valid
return recievedHash == QCryptographicHash::hash(message, HashAlgorithm::Sha256);
}
QRSAEncryption::Rsa QRSAEncryption::getRsa() const {
return _rsa;
}
bool QRSAEncryption::testKeyPair(const QByteArray &pubKey, const QByteArray &privKey) {
QByteArray tesVal = "Test message of encrypkey";
bool result = tesVal == decode(encode(tesVal, pubKey), privKey);
if (!result) qWarning() << "(Warning): Testkey Fail, try generate new key pair!";
return result;
}
// --- end of non-static methods ---
bool QRSAEncryption::isValidRsaKey(const QByteArray &key) {
return key.size() && ((static_cast<unsigned int>(key.size()) % getKeyBytesSize(RSA_64)) == 0);
}
//#
//# Copyright (C) 2018-2019 QuasarApp.
//# Distributed under the lgplv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#ifndef QRSAENCRYPTION_H
#define QRSAENCRYPTION_H
#include <QByteArray>
#include <QList>
#include <QFile>
#include <cmath>
#include <QDebug>
#include <QCryptographicHash> // to use sha256
#include "./../qtsecret_global.h"
#include <bigint.h>
class Qt_SECRETSHARED_EXPORT QRSAEncryption
{
public:
typedef BigInt INT;
typedef QCryptographicHash::Algorithm HashAlgorithm;
enum Rsa {
Invalid = 0,
RSA_64 = 64,
RSA_128 = 128,
RSA_256 = 256,
RSA_512 = 512,
RSA_1024 = 1024,
RSA_2048 = 2048,
RSA_4096 = 4096,
RSA_8192 = 8192,
};
enum BlockSize {
Auto = 0, // fast but not stable. (using by default)
OneByte = 1 // stable but slow. (using for sig and check sig messages)
};
QRSAEncryption(Rsa rsa = Rsa::RSA_256);
// static methods
// OLDMETHODS DELETE IN next Version
static bool generatePairKeyS(QByteArray &pubKey, QByteArray &privKey,
QRSAEncryption::Rsa rsa = RSA_256);
static QByteArray encodeS(const QByteArray &rawData, const QByteArray &pubKey,
Rsa rsa = RSA_256, BlockSize blockSizeMode = BlockSize::Auto);
static QByteArray decodeS(const QByteArray &rawData, const QByteArray &privKey,
Rsa rsa = RSA_256, BlockSize blockSizeMode = BlockSize::Auto);
static QByteArray signMessageS(QByteArray rawData, const QByteArray &privKey,
Rsa rsa = RSA_256);
static bool checkSignMessageS(const QByteArray &rawData, const QByteArray &pubKey,
Rsa rsa);
// OLDMETHODS END
static bool generatePairKey(QByteArray &pubKey, QByteArray &privKey,
QRSAEncryption::Rsa rsa);
static QByteArray encode(const QByteArray &rawData, const QByteArray &pubKey,
Rsa rsa, BlockSize blockSizeMode = BlockSize::Auto);
static QByteArray decode(const QByteArray &rawData, const QByteArray &privKey,
Rsa rsa, BlockSize blockSizeMode = BlockSize::Auto);
static QByteArray signMessage(QByteArray rawData, const QByteArray &privKey,
Rsa rsa);
static bool checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey,
Rsa rsa);
static bool isValidRsaKey(const QByteArray& key);
static unsigned int getKeyBytesSize(QRSAEncryption::Rsa rsa);
// non-static methods
bool generatePairKey(QByteArray &pubKey, QByteArray &privKey);
QByteArray encode(const QByteArray &rawData, const QByteArray &pubKey,
BlockSize blockSizeMode = BlockSize::Auto);
QByteArray decode(const QByteArray &rawData, const QByteArray &privKey,
BlockSize blockSizeMode = BlockSize::Auto);
QByteArray signMessage(QByteArray rawData, const QByteArray &privKey);
bool checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey);
Rsa getRsa() const;
private:
Rsa _rsa;
bool testKeyPair(const QByteArray &pubKey, const QByteArray &privKey);
bool isMutuallyPrime(const INT &a, const INT &b);
Rsa getBitsSize(const INT& i) const;
Rsa getBitsSize(const QByteArray& array) const;
INT fromArray(const QByteArray& array) const;
QByteArray toArray(const INT &i, short sizeBlok = -1);
INT randomNumber(bool fullFilled = true) const;
INT toPrime(INT) const;
INT randomPrimeNumber(INT no = 0) const;
INT extEuclid(INT a, INT b) const;
short getBlockSize(INT i) const;
QByteArray encodeBlok(const INT& block, const INT& e, const INT& m, short blockSize);
QByteArray decodeBlok(const INT& block, const INT& d, const INT& m, short blockSize);
};
#endif // QRSAENCRYPTION_H
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
!isEmpty(Qt_SECRET_LIB):error("Qt-Secret.pri already included")
Qt_SECRET_LIB = 1
#DEPENDS
CONFIG(release, debug|release): {
Qt_SECRET_LIB_OUTPUT_DIR="$$PWD/build/release"
} else {
Qt_SECRET_LIB_OUTPUT_DIR="$$PWD/build/debug"
}
unix:LIBS += -L$$Qt_SECRET_LIB_OUTPUT_DIR -lQt-Secret
win32:LIBS += -L$$Qt_SECRET_LIB_OUTPUT_DIR -lQt-Secret1
include($$PWD/mini-gmp/src/GMPIncudePah.pri)
INCLUDEPATH += "$$PWD/Qt-RSA"
INCLUDEPATH += "$$PWD/Qt-AES"
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
QT -= gui
CONFIG += c++11
TARGET = Qt-Secret
TEMPLATE = lib
DEFINES += Qt_SECRET_LIBRARY
DEFINES += QT_DEPRECATED_WARNINGS
#DEPENDS
CONFIG(release, debug|release): {
DESTDIR="$$PWD/build/release"
} else {
DESTDIR="$$PWD/build/debug"
}
include($$PWD/mini-gmp/GMP.pri)
VERSION = 1.2.0
HEADERS += \
qtsecret_global.h \
Qt-RSA/qrsaencryption.h
SOURCES += \
Qt-RSA/qrsaencryption.cpp
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
include($$PWD/src/GMP.pri)
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
TEMPLATE = subdirs
CONFIG += ordered
SUBDIRS += \
src
src.file = src/GMP.pro
MIT License
Copyright (c) 2019 QuasarApp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
!isEmpty(Qt_GMP_LIB):error("GMP.pri already included")
Qt_GMP_LIB = 1
#DEPENDS
CONFIG(release, debug|release): {
MINIGMP_LIBRARY_OUTPUT_DIR="$$PWD/build/release"
} else {
MINIGMP_LIBRARY_OUTPUT_DIR="$$PWD/build/debug"
}
unix:LIBS += -L$$MINIGMP_LIBRARY_OUTPUT_DIR -lQtBigInt
win32:LIBS += -L$$MINIGMP_LIBRARY_OUTPUT_DIR -lQtBigInt
include(GMPIncudePah.pri)
include(ccache.pri);
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
QT -= core gui
TARGET = MiniGMP
TEMPLATE = lib
DEFINES += MINIGMP_LIBRARY
DEFINES += QT_DEPRECATED_WARNINGS
TARGET = QtBigInt
CONFIG += static
VERSION = 6.1.2
CONFIG(release, debug|release): {
DESTDIR="$$PWD/build/release"
} else {
DESTDIR="$$PWD/build/debug"
}
DISTFILES += \
README \
HEADERS += \
bigint.h \
mini-gmp.h \
minigmp_global.h
SOURCES += \
bigint.cpp \
mini-gmp.c
include(ccache.pri);
#
# Copyright (C) 2018-2019 QuasarApp.
# Distributed under the lgplv3 software license, see the accompanying
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
INCLUDEPATH += "$$PWD"
obj-m += minigmp.o
minigmp-objs := mini-gmp.o export.o
EXTRA_CFLAGS+=-DKERNEL=1
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
//#
//# Copyright (C) 2018-2019 QuasarApp.
//# Distributed under the lgplv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#include "bigint.h"
#include <limits>
#include <cstring>
#include <cmath>
// constructors
BigInt::BigInt() {
mpz_init(data);
}
BigInt::BigInt(const BigInt &val, int bitCount) {
if (bitCount > 0) {
mpz_init2(data, static_cast<unsigned int>(bitCount));
} else {
mpz_init(data);
}
mpz_set(data, val.data);
}
BigInt::BigInt(const std::string &str, int base):
BigInt() {
mpz_set_str(data, str.c_str(), base);
}
BigInt::BigInt(intMpz val):
BigInt() {
mpz_set_si(data, val);
}
BigInt::BigInt(char item, unsigned int size, int base = 2):
BigInt(std::string(size, item),base) {
}
std::string BigInt::getString(int base) const {
char *str = mpz_get_str(nullptr, base, data);
return str;
}
BigInt::~BigInt() {
mpz_clear(data);
}
BigInt &BigInt::powm(const BigInt &pow, const BigInt &mod) {
mpz_powm(data, data, pow.data, mod.data);
return *this;
}
BigInt BigInt::powm(BigInt val, const BigInt &pow, const BigInt &mod) {
return val.powm(pow, mod);
}
BigInt &BigInt::pow(uIntMpz pow) {
mpz_pow_ui(data, data, pow);
return *this;
}
int BigInt::sizeBits() const {
return sizeBytes() * 8;
}
int BigInt::sizeBytes() const {
return static_cast<int>(mpz_size(data) * sizeof ((*data->_mp_d)));
}
int BigInt::longBits() const {
return static_cast<int>(getString(2).size());
}
int BigInt::longBytes() const {
return static_cast<int>(std::ceil(static_cast<double>(longBits()) / 8));
}
#define GMP_ABS(x) ((x) >= 0 ? (x) : -(x))
int BigInt::sizeType() const {
return static_cast<int>(static_cast<size_t>(GMP_ABS( data->_mp_alloc)) *
sizeof ((*data->_mp_d)));
}
bool BigInt::isPrime(bool absalut) const {
return (mpz_probab_prime_p(data, 50) - (absalut? 1: 0)) > 0;
}
BigInt& BigInt::gcd(const BigInt &a, const BigInt &b) {
mpz_gcd(data, a.data, b.data);
return *this;
}
void BigInt::fromHex(const std::string &hex) {
mpz_set_str(data, hex.c_str(), 16);
}
BigInt BigInt::bigPow10(unsigned short pow) {
return "1" + std::string(pow, '0');
}
BigInt &BigInt::toNegative() {
mpz_neg(data, data);
return *this;
}
BigInt &BigInt::operator =(const BigInt &val) {
mpz_set(data, val.data);
return *this;
}
BigInt &BigInt::operator =(const std::string &imput) {
mpz_set_str(data, imput.c_str(), 10);
return *this;
}
BigInt &BigInt::operator =(intMpz val) {
mpz_set_si(data, val);
return *this;
}
// add operators
BigInt operator +(BigInt left, intMpz right) {
if (right >= 0) {
mpz_add_ui(left.data, left.data, static_cast<uIntMpz>(right));
return left;
}
return left -= std::abs(right);
}
BigInt operator +(intMpz left, BigInt right) {
return right += left;
}
BigInt operator +(BigInt left, const BigInt &right) {
mpz_add(left.data, left.data, right.data);
return left;
}
BigInt operator +(BigInt left, const std::string &right) {
return left += BigInt(right);
}
BigInt operator +(const std::string &left, const BigInt &right) {
return BigInt(left) + right;
}
BigInt& operator +=(BigInt &left, intMpz right) {
if (right >= 0) {
mpz_add_ui(left.data, left.data, static_cast<uIntMpz>(right));
return left;
}
return left -= std::abs(right);
}
BigInt& operator +=(BigInt &left, const BigInt &right) {
mpz_add(left.data, left.data, right.data);
return left;
}
BigInt& operator +=(BigInt &left, const std::string &right) {
return left += BigInt(right);
}
// sub operators
BigInt operator -(BigInt left, const BigInt &right) {
mpz_sub(left.data, left.data, right.data);
return left;
}
BigInt operator -(BigInt left, intMpz right) {
if (right >= 0) {
mpz_sub_ui(left.data, left.data, static_cast<uIntMpz>(right));
return left;
}
return left += std::abs(right);
}
BigInt operator -(intMpz left, BigInt right) {
if (left >= 0) {
mpz_ui_sub(right.data, static_cast<uIntMpz>(left), right.data);
return right;
}
return right += std::abs(left);
}
BigInt operator-(BigInt val) {
mpz_neg(val.data, val.data);
return val;
}
BigInt operator -(BigInt left, const std::string &right) {
return left -= BigInt(right);
}
BigInt operator -(const std::string & left, const BigInt &right) {
return BigInt(left) - right;
}
BigInt& operator -=(BigInt &left, const BigInt &right) {
mpz_sub(left.data, left.data, right.data);
return left;
}
BigInt& operator -=(BigInt &left, const std::string &right) {
return left -= BigInt(right);
}
BigInt& operator -=(BigInt &left, intMpz right) {
if (right >= 0) {
mpz_sub_ui(left.data, left.data, static_cast<uIntMpz>(right));
return left;
}
return left += std::abs(right);
}
// div operators
BigInt operator /(BigInt left, const BigInt &right) {
mpz_tdiv_q(left.data, left.data, right.data);
return left;
}
BigInt operator /(BigInt left, intMpz right) {
mpz_tdiv_q_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
if (right >= 0) {
return left;
}
return -left;
}
BigInt operator /(BigInt left, const std::string &right) {
return left /= BigInt(right);
}
BigInt operator /(intMpz left, BigInt right) {
return BigInt(left) / right;
}
BigInt operator /(const std::string & left, const BigInt &right) {
return BigInt(left) / right;
}
BigInt& operator /=(BigInt &left, const BigInt &right) {
mpz_tdiv_q(left.data, left.data, right.data);
return left;
}
BigInt& operator /=(BigInt &left, const std::string &right) {
return left /= BigInt(right);
}
BigInt& operator /=(BigInt &left, intMpz right) {
mpz_tdiv_q_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
if (right >= 0) {
return left;
}
return left.toNegative();
}
// mul operators
BigInt operator *(BigInt left, const BigInt &right) {
mpz_mul(left.data, left.data, right.data);
return left;
}
BigInt operator *(BigInt left, intMpz right) {
mpz_mul_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
if (right >= 0) {
return left;
}
return -left;
}
BigInt operator *(intMpz left, BigInt right) {
return right *= left;
}
BigInt operator *(const std::string & left, BigInt right) {
return right *= BigInt(left);
}
BigInt operator *(BigInt left, const std::string &right) {
return left *= BigInt(right);
}
BigInt& operator *=(BigInt &left, const BigInt &right) {
mpz_mul(left.data, left.data, right.data);
return left;
}
BigInt& operator *=(BigInt &left, const std::string &right) {
return left *= BigInt(right);
}
BigInt& operator *=(BigInt &left, intMpz right) {
mpz_mul_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
if (right >= 0) {
return left;
}
return left.toNegative();
}
//mod operations
BigInt operator %(BigInt left, const BigInt &right) {
mpz_tdiv_r(left.data, left.data, right.data);
return left;
}
BigInt operator %(BigInt left, intMpz right) {
mpz_tdiv_r_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
return left;
}
BigInt operator %(intMpz left, BigInt right) {
return BigInt(left) % right;
}
BigInt operator %(BigInt left, const std::string & right) {
return left %= BigInt(right);
}
BigInt operator %(const std::string & left, const BigInt &right) {
return BigInt(left) % right;
}
BigInt& operator %=(BigInt& left, const BigInt &right) {
mpz_tdiv_r(left.data, left.data, right.data);
return left;
}
BigInt& operator %=(BigInt& left, intMpz right) {
mpz_tdiv_r_ui(left.data, left.data, static_cast<uIntMpz>(std::abs(right)));
return left;
}
BigInt& operator %=(BigInt &left, const std::string &right) {
return left %= BigInt(right);
}
// incriment and dicriment
BigInt &BigInt::operator--() {
*this -= 1;
return *this;
}
BigInt &BigInt::operator++() {
*this += 1;
return *this;
}
BigInt BigInt::operator--(int) {
BigInt temp(*this);
--*this;
return temp;
}
BigInt BigInt::operator++(int) {
BigInt temp(*this);
++*this;
return temp;
}
// move operators
BigInt operator >>(BigInt left, int right) {
if (right >= 0) {
mpn_rshift(left.data->_mp_d,
left.data->_mp_d,
left.data->_mp_size,
static_cast<unsigned int>(std::abs(right)));
return left;
}
return left << right;
}
BigInt operator <<(BigInt left, int right) {
if (right >= 0) {
mpn_lshift(left.data->_mp_d,
left.data->_mp_d,
left.data->_mp_size,
static_cast<unsigned int>(std::abs(right)));
return left;
}
return left >> right;
}
BigInt& operator >>=(BigInt &left, int right) {
if (right >= 0) {
mpn_rshift(left.data->_mp_d,
left.data->_mp_d,
left.data->_mp_size,
static_cast<unsigned int>(std::abs(right)));
return left;
}
return left <<= right;
}
BigInt& operator <<=(BigInt &left, int right) {
if (right >= 0) {
mpn_lshift(left.data->_mp_d,
left.data->_mp_d,
left.data->_mp_size,
static_cast<unsigned int>(std::abs(right)));
return left;
}
return left >>= right;
}
// other bin operators
BigInt operator ~(BigInt left) {
mpz_com(left.data, left.data);
return left;
}
BigInt operator |(BigInt left, const BigInt &right) {
mpz_ior(left.data, left.data, right.data);
return left;
}
BigInt operator |(const BigInt &left, intMpz right) {
return left | BigInt(right);
}
BigInt& operator |=(BigInt &left, const BigInt &right) {
mpz_ior(left.data, left.data, right.data);
return left;
}
BigInt& operator |=(BigInt &left, intMpz right) {
return left |= BigInt(right);
}
BigInt operator &(BigInt left, const BigInt &right) {
mpz_and(left.data, left.data, right.data);
return left;
}
BigInt operator &(const BigInt &left, intMpz right) {
return left & BigInt(right);
}
BigInt& operator &=(BigInt &left, const BigInt &right) {
mpz_and(left.data, left.data, right.data);
return left;
}
BigInt& operator &=(BigInt &left, intMpz right) {
return left &= BigInt(right);
}
BigInt operator ^(BigInt left, const BigInt &right) {
mpz_xor(left.data, left.data, right.data);
return left;
}
BigInt operator ^(const BigInt &left, intMpz right) {
return left ^ BigInt(right);
}
BigInt& operator ^=(BigInt &left, const BigInt &right) {
mpz_xor(left.data, left.data, right.data);
return left;
}
BigInt& operator ^=(BigInt &left, intMpz right) {
return left ^= BigInt(right);
}
// logic operators
bool operator!(const BigInt &val) {
return val == 0;
}
bool operator == (const BigInt& left, const BigInt& right) {
return mpz_cmp(left.data, right.data) == 0;
}
bool operator == (const BigInt& left, intMpz right) {
return mpz_cmp_si(left.data, right) == 0;
}
bool operator == (const BigInt &left, const std::string &right) {
return left == BigInt(right);
}
bool operator == ( intMpz left, const BigInt & right) {
return right == left;
}
bool operator == ( const std::string & left, const BigInt & right) {
return right == BigInt(left);
}
bool operator != (const BigInt &left, const BigInt& right) {
return !(left == right);
}
bool operator != (const BigInt &left, intMpz right) {
return !(left == right);
}
bool operator != (const BigInt &left, const std::string &right) {
return left != BigInt(right);
}
bool operator != ( intMpz left, const BigInt & right) {
return right != left;
}
bool operator != ( const std::string & left, const BigInt & right) {
return right != BigInt(left);
}
bool operator < ( const BigInt &left, const BigInt& right) {
return mpz_cmp(left.data, right.data) < 0;
}
bool operator < ( const BigInt &left, intMpz right) {
return mpz_cmp_si(left.data, right) < 0;
}
bool operator < ( const BigInt &left, const std::string &right) {
return left < BigInt(right);
}
bool operator < ( intMpz left, const BigInt & right) {
return right > left;
}
bool operator < ( const std::string & left, const BigInt & right) {
return right > BigInt(left);
}
bool operator > ( const BigInt &left, const BigInt& right) {
return mpz_cmp(left.data, right.data) > 0;
}
bool operator > ( const BigInt &left, intMpz right) {
return mpz_cmp_si(left.data, right) > 0;
}
bool operator > ( const BigInt &left, const std::string &right) {
return left > BigInt(right);
}
bool operator > ( intMpz left, const BigInt & right) {
return right < left;
}
bool operator > ( const std::string & left, const BigInt & right) {
return right < BigInt(left);
}
bool operator <= ( const BigInt &left, const BigInt& right) {
return mpz_cmp(left.data, right.data) <= 0;
}
bool operator <= ( const BigInt &left, intMpz right) {
return mpz_cmp_si(left.data, right) <= 0;
}
bool operator <= ( const BigInt &left, const std::string &right) {
return left <= BigInt(right);
}
bool operator <= ( intMpz left, const BigInt & right) {
return right >= left;
}
bool operator <= ( const std::string & left, const BigInt & right) {
return right >= BigInt(left);
}
bool operator >= ( const BigInt &left, const BigInt& right) {
return mpz_cmp(left.data, right.data) >= 0;
}
bool operator >= ( const BigInt &left, intMpz right) {
return mpz_cmp_si(left.data, right) >= 0;
}
bool operator >= ( const BigInt &left, const std::string &right) {
return left >= BigInt(right);
}
bool operator >= ( intMpz left, const BigInt & right) {
return right <= left;
}
bool operator >= ( const std::string & left, const BigInt & right) {
return right <= BigInt(left);
}
//// cast operations
//BigInt::operator bool() const {
// return *this != 0;
//}
//#
//# Copyright (C) 2018-2019 QuasarApp.
//# Distributed under the lgplv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#ifndef BIGINT_H
#define BIGINT_H
#include "mini-gmp.h"
#include <string>
#include <vector>
#include "minigmp_global.h"
/**
* @brief The BigInt class - c++ minigmp wrapper
*/
class MINIGMPSHARED_EXPORT BigInt
{
mpz_t data;
public:
BigInt();
BigInt(const BigInt& val, int bitCount = -1);
BigInt(const std::string &imput, int base = 10);
BigInt(intMpz val);
BigInt(char item, unsigned int size, int base);
std::string getString(int base = 10) const;
~BigInt();
BigInt& powm(const BigInt &pow, const BigInt &mod);
static BigInt powm(BigInt val, const BigInt & pow, const BigInt &mod);
BigInt& pow(uIntMpz pow);
BigInt& log(int base);
/**
* @brief sizeBits
* @return size of bits in memory
*/
int sizeBits() const;
int sizeBytes() const;
/**