From 9d3218ec547901ebec6dd546a65f4b2db01128b6 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Mon, 4 Mar 2024 18:06:57 +0700 Subject: Refactor RSA engines --- crypto/src/crypto/engines/RSABlindedEngine.cs | 40 ++++++++++----------------- crypto/src/crypto/engines/RSACoreEngine.cs | 4 +-- 2 files changed, 16 insertions(+), 28 deletions(-) (limited to 'crypto') diff --git a/crypto/src/crypto/engines/RSABlindedEngine.cs b/crypto/src/crypto/engines/RSABlindedEngine.cs index 8bb9a4f8c..63b8bbf69 100644 --- a/crypto/src/crypto/engines/RSABlindedEngine.cs +++ b/crypto/src/crypto/engines/RSABlindedEngine.cs @@ -41,34 +41,17 @@ namespace Org.BouncyCastle.Crypto.Engines */ public virtual void Init(bool forEncryption, ICipherParameters param) { - core.Init(forEncryption, param); - - if (param is ParametersWithRandom rParam) + SecureRandom providedRandom = null; + if (param is ParametersWithRandom withRandom) { - this.key = (RsaKeyParameters)rParam.Parameters; - - if (key is RsaPrivateCrtKeyParameters) - { - this.random = rParam.Random; - } - else - { - this.random = null; - } - } - else - { - this.key = (RsaKeyParameters)param; - - if (key is RsaPrivateCrtKeyParameters) - { - this.random = CryptoServicesRegistrar.GetSecureRandom(); - } - else - { - this.random = null; - } + providedRandom = withRandom.Random; + param = withRandom.Parameters; } + + core.Init(forEncryption, param); + + this.key = (RsaKeyParameters)param; + this.random = InitSecureRandom(needed: key is RsaPrivateCrtKeyParameters, providedRandom); } /** @@ -114,6 +97,11 @@ namespace Org.BouncyCastle.Crypto.Engines return core.ConvertOutput(result); } + protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided) + { + return needed ? CryptoServicesRegistrar.GetSecureRandom(provided) : null; + } + private BigInteger ProcessInput(BigInteger input) { if (!(key is RsaPrivateCrtKeyParameters crt)) diff --git a/crypto/src/crypto/engines/RSACoreEngine.cs b/crypto/src/crypto/engines/RSACoreEngine.cs index 7040899f9..dcc8d0101 100644 --- a/crypto/src/crypto/engines/RSACoreEngine.cs +++ b/crypto/src/crypto/engines/RSACoreEngine.cs @@ -116,10 +116,10 @@ namespace Org.BouncyCastle.Crypto.Engines BigInteger qInv = crt.QInv; // mP = ((input Mod p) ^ dP)) Mod p - BigInteger mP = (input.Remainder(p)).ModPow(dP, p); + BigInteger mP = input.Remainder(p).ModPow(dP, p); // mQ = ((input Mod q) ^ dQ)) Mod q - BigInteger mQ = (input.Remainder(q)).ModPow(dQ, q); + BigInteger mQ = input.Remainder(q).ModPow(dQ, q); // h = qInv * (mP - mQ) Mod p BigInteger h = mP.Subtract(mQ).Multiply(qInv).Mod(p); -- cgit 1.4.1