Skip to content

Commit 57cc248

Browse files
devgianlualimpfard
authored andcommitted
LibCrypto: Add optimized RSA decryption with CRT method
The textbook RSA decryption method of `c^d % n` is quite slow. If the necessary parameters are present, the CRT variant will be used. Performing RSA decryption this way is ~3 times faster.
1 parent ec990d6 commit 57cc248

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

Libraries/LibCrypto/PK/RSA.cpp

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,24 @@ void RSA::encrypt(ReadonlyBytes in, Bytes& out)
133133

134134
void RSA::decrypt(ReadonlyBytes in, Bytes& out)
135135
{
136-
// FIXME: Actually use the private key properly
137-
138136
auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
139-
auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
140-
auto size = exp.export_data(out);
141137

138+
UnsignedBigInteger m;
139+
if (m_private_key.prime1().is_zero() || m_private_key.prime2().is_zero()) {
140+
m = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
141+
} else {
142+
auto m1 = NumberTheory::ModularPower(in_integer, m_private_key.exponent1(), m_private_key.prime1());
143+
auto m2 = NumberTheory::ModularPower(in_integer, m_private_key.exponent2(), m_private_key.prime2());
144+
if (m1 < m2)
145+
m1 = m1.plus(m_private_key.prime1());
146+
147+
VERIFY(m1 >= m2);
148+
149+
auto h = NumberTheory::Mod(m1.minus(m2).multiplied_by(m_private_key.coefficient()), m_private_key.prime1());
150+
m = m2.plus(h.multiplied_by(m_private_key.prime2()));
151+
}
152+
153+
auto size = m.export_data(out);
142154
auto align = m_private_key.length();
143155
auto aligned_size = (size + align - 1) / align * align;
144156

0 commit comments

Comments
 (0)