DsaKeyPairGenerator.cs 2.5 KB

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