我正嘗試使用彈性城堡.net庫來執行Diffie-Hellman密鑰交換,並在生成DHParams對象時遇到問題。Bouncy Castle Diffie-Hellman DHParams問題
我的解決方案將包括一箇中央權威機構,它將爲每個連接的客戶端生成一個單獨的DH密鑰/對。這個想法是,我將爲每個連接的客戶端保留一個單獨的DH密鑰協議。然後,我將把p,g值發送給客戶端,客戶端將計算它的dh密鑰協議。我想爲每個客戶端生成不同的p,g值。我正在使用BigInteger,但遇到了一些問題。
當我嘗試創建一個新的對象DHParameters它拋出以下異常,每當我用比其他768位長:
System.ArgumentException was unhandled
Message="generator must in the range [2, p - 2]\r\nParameter name: g"
Source="BouncyCastle.Crypto"
ParamName="g"
StackTrace:
at Org.BouncyCastle.Crypto.Parameters.DHParameters..ctor(BigInteger p, BigInteger g, BigInteger q, Int32 m, Int32 l, BigInteger j, DHValidationParameters validation)
at Org.BouncyCastle.Crypto.Parameters.DHParameters..ctor(BigInteger p, BigInteger g, BigInteger q, Int32 l)
at TestDH.Program.Main(String[] args) in C:\dev\source\TestDH\TestDH\Program.cs:line 30
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
"generator must in the range [2, p - 2]"
我不知道,如果它的問題,但我已經試過各種在BigInteger構造函數中確定不同的值。
這裏是我的代碼:
SecureRandom sr = new SecureRandom();
// p,g generation, done by central authority
BigInteger g512 = new BigInteger(512, 30, sr);
BigInteger p512 = new BigInteger(512, 30, sr);
// p,g is then sent to client from central authority
// common - performed by both server and client sides
IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
DHParameters dhParams = new DHParameters(p512, g512, null, 512); // Here is where I get the exception if the first parameter if BigInteger is not 768 or lager
的問題是,它的時間太長,產生768位的素數 - 上沒有其他進程運行的雙核2.1GHz的處理器向上的5秒。對於每個啓動連接的客戶端而言,這都會帶來很大的代價。我想爲BigInteger使用較小的比特長度。
我可能這樣做完全錯誤 - 關於如何使用彈性城堡執行DH以及測試/示例與我的使用案例不匹配,文檔很少。我不想預先生成p,g值。
編輯 看來即使是768位長度也會在一段時間內出錯。重新啓動我的機器後,除1024以外的任何位都可以工作,即使這樣也只有大約80%的時間。我覺得我做錯了什麼。