GOST3410KeyPairGenerator.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
  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. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
  10. {
  11. /**
  12. * a GOST3410 key pair generator.
  13. * This generates GOST3410 keys in line with the method described
  14. * in GOST R 34.10-94.
  15. */
  16. public class Gost3410KeyPairGenerator
  17. : IAsymmetricCipherKeyPairGenerator
  18. {
  19. private Gost3410KeyGenerationParameters param;
  20. public void Init(
  21. KeyGenerationParameters parameters)
  22. {
  23. if (parameters is Gost3410KeyGenerationParameters)
  24. {
  25. this.param = (Gost3410KeyGenerationParameters) parameters;
  26. }
  27. else
  28. {
  29. Gost3410KeyGenerationParameters kgp = new Gost3410KeyGenerationParameters(
  30. parameters.Random,
  31. CryptoProObjectIdentifiers.GostR3410x94CryptoProA);
  32. if (parameters.Strength != kgp.Parameters.P.BitLength - 1)
  33. {
  34. // TODO Should we complain?
  35. }
  36. this.param = kgp;
  37. }
  38. }
  39. public AsymmetricCipherKeyPair GenerateKeyPair()
  40. {
  41. SecureRandom random = param.Random;
  42. Gost3410Parameters gost3410Params = param.Parameters;
  43. BigInteger q = gost3410Params.Q, x;
  44. int minWeight = 64;
  45. for (;;)
  46. {
  47. x = new BigInteger(256, random);
  48. if (x.SignValue < 1 || x.CompareTo(q) >= 0)
  49. continue;
  50. if (WNafUtilities.GetNafWeight(x) < minWeight)
  51. continue;
  52. break;
  53. }
  54. BigInteger p = gost3410Params.P;
  55. BigInteger a = gost3410Params.A;
  56. // calculate the public key.
  57. BigInteger y = a.ModPow(x, p);
  58. if (param.PublicKeyParamSet != null)
  59. {
  60. return new AsymmetricCipherKeyPair(
  61. new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
  62. new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet));
  63. }
  64. return new AsymmetricCipherKeyPair(
  65. new Gost3410PublicKeyParameters(y, gost3410Params),
  66. new Gost3410PrivateKeyParameters(x, gost3410Params));
  67. }
  68. }
  69. }
  70. #pragma warning restore
  71. #endif