DsaKeyPairGenerator.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
  11. {
  12. /**
  13. * a DSA key pair generator.
  14. *
  15. * This Generates DSA keys in line with the method described
  16. * in <i>FIPS 186-3 B.1 FFC Key Pair Generation</i>.
  17. */
  18. public class DsaKeyPairGenerator
  19. : IAsymmetricCipherKeyPairGenerator
  20. {
  21. private static readonly BigInteger One = BigInteger.One;
  22. private DsaKeyGenerationParameters param;
  23. public void Init(
  24. KeyGenerationParameters parameters)
  25. {
  26. if (parameters == null)
  27. throw new ArgumentNullException("parameters");
  28. // Note: If we start accepting instances of KeyGenerationParameters,
  29. // must apply constraint checking on strength (see DsaParametersGenerator.Init)
  30. this.param = (DsaKeyGenerationParameters) parameters;
  31. }
  32. public AsymmetricCipherKeyPair GenerateKeyPair()
  33. {
  34. DsaParameters dsaParams = param.Parameters;
  35. BigInteger x = GeneratePrivateKey(dsaParams.Q, param.Random);
  36. BigInteger y = CalculatePublicKey(dsaParams.P, dsaParams.G, x);
  37. return new AsymmetricCipherKeyPair(
  38. new DsaPublicKeyParameters(y, dsaParams),
  39. new DsaPrivateKeyParameters(x, dsaParams));
  40. }
  41. private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
  42. {
  43. // B.1.2 Key Pair Generation by Testing Candidates
  44. int minWeight = q.BitLength >> 2;
  45. for (;;)
  46. {
  47. // TODO Prefer this method? (change test cases that used fixed random)
  48. // B.1.1 Key Pair Generation Using Extra Random Bits
  49. //BigInteger x = new BigInteger(q.BitLength + 64, random).Mod(q.Subtract(One)).Add(One);
  50. BigInteger x = BigIntegers.CreateRandomInRange(One, q.Subtract(One), random);
  51. if (WNafUtilities.GetNafWeight(x) >= minWeight)
  52. {
  53. return x;
  54. }
  55. }
  56. }
  57. private static BigInteger CalculatePublicKey(BigInteger p, BigInteger g, BigInteger x)
  58. {
  59. return g.ModPow(x, p);
  60. }
  61. }
  62. }
  63. #pragma warning restore
  64. #endif