PublicKeyFactory.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using System.Text;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
  14. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  15. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
  16. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  17. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
  18. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  19. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  20. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
  21. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  22. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
  23. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
  24. {
  25. public sealed class PublicKeyFactory
  26. {
  27. private PublicKeyFactory()
  28. {
  29. }
  30. public static AsymmetricKeyParameter CreateKey(
  31. byte[] keyInfoData)
  32. {
  33. return CreateKey(
  34. SubjectPublicKeyInfo.GetInstance(
  35. Asn1Object.FromByteArray(keyInfoData)));
  36. }
  37. public static AsymmetricKeyParameter CreateKey(
  38. Stream inStr)
  39. {
  40. return CreateKey(
  41. SubjectPublicKeyInfo.GetInstance(
  42. Asn1Object.FromStream(inStr)));
  43. }
  44. public static AsymmetricKeyParameter CreateKey(
  45. SubjectPublicKeyInfo keyInfo)
  46. {
  47. AlgorithmIdentifier algID = keyInfo.AlgorithmID;
  48. DerObjectIdentifier algOid = algID.Algorithm;
  49. // TODO See RSAUtil.isRsaOid in Java build
  50. if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
  51. || algOid.Equals(X509ObjectIdentifiers.IdEARsa)
  52. || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
  53. || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
  54. {
  55. RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
  56. keyInfo.ParsePublicKey());
  57. return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent);
  58. }
  59. else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
  60. {
  61. Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
  62. DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.ParsePublicKey());
  63. BigInteger y = dhPublicKey.Y.Value;
  64. if (IsPkcsDHParam(seq))
  65. return ReadPkcsDHParam(algOid, y, seq);
  66. DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);
  67. BigInteger p = dhParams.P.Value;
  68. BigInteger g = dhParams.G.Value;
  69. BigInteger q = dhParams.Q.Value;
  70. BigInteger j = null;
  71. if (dhParams.J != null)
  72. {
  73. j = dhParams.J.Value;
  74. }
  75. DHValidationParameters validation = null;
  76. DHValidationParms dhValidationParms = dhParams.ValidationParms;
  77. if (dhValidationParms != null)
  78. {
  79. byte[] seed = dhValidationParms.Seed.GetBytes();
  80. BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;
  81. // TODO Check pgenCounter size?
  82. validation = new DHValidationParameters(seed, pgenCounter.IntValue);
  83. }
  84. return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
  85. }
  86. else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
  87. {
  88. Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
  89. DerInteger derY = (DerInteger)keyInfo.ParsePublicKey();
  90. return ReadPkcsDHParam(algOid, derY.Value, seq);
  91. }
  92. else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
  93. {
  94. ElGamalParameter para = new ElGamalParameter(
  95. Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
  96. DerInteger derY = (DerInteger)keyInfo.ParsePublicKey();
  97. return new ElGamalPublicKeyParameters(
  98. derY.Value,
  99. new ElGamalParameters(para.P, para.G));
  100. }
  101. else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)
  102. || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
  103. {
  104. DerInteger derY = (DerInteger)keyInfo.ParsePublicKey();
  105. Asn1Encodable ae = algID.Parameters;
  106. DsaParameters parameters = null;
  107. if (ae != null)
  108. {
  109. DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
  110. parameters = new DsaParameters(para.P, para.Q, para.G);
  111. }
  112. return new DsaPublicKeyParameters(derY.Value, parameters);
  113. }
  114. else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
  115. {
  116. X962Parameters para = X962Parameters.GetInstance(algID.Parameters.ToAsn1Object());
  117. X9ECParameters x9;
  118. if (para.IsNamedCurve)
  119. {
  120. x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
  121. }
  122. else
  123. {
  124. x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
  125. }
  126. Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
  127. X9ECPoint derQ = new X9ECPoint(x9.Curve, key);
  128. ECPoint q = derQ.Point;
  129. if (para.IsNamedCurve)
  130. {
  131. return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters);
  132. }
  133. ECDomainParameters dParams = new ECDomainParameters(x9);
  134. return new ECPublicKeyParameters(q, dParams);
  135. }
  136. else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
  137. {
  138. Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
  139. DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet;
  140. X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(publicKeyParamSet);
  141. if (ecP == null)
  142. return null;
  143. Asn1OctetString key;
  144. try
  145. {
  146. key = (Asn1OctetString)keyInfo.ParsePublicKey();
  147. }
  148. catch (IOException e)
  149. {
  150. throw new ArgumentException("error recovering GOST3410_2001 public key", e);
  151. }
  152. int fieldSize = 32;
  153. int keySize = 2 * fieldSize;
  154. byte[] keyEnc = key.GetOctets();
  155. if (keyEnc.Length != keySize)
  156. throw new ArgumentException("invalid length for GOST3410_2001 public key");
  157. byte[] x9Encoding = new byte[1 + keySize];
  158. x9Encoding[0] = 0x04;
  159. for (int i = 1; i <= fieldSize; ++i)
  160. {
  161. x9Encoding[i] = keyEnc[fieldSize - i];
  162. x9Encoding[i + fieldSize] = keyEnc[keySize - i];
  163. }
  164. ECPoint q = ecP.Curve.DecodePoint(x9Encoding);
  165. return new ECPublicKeyParameters("ECGOST3410", q, publicKeyParamSet);
  166. }
  167. else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
  168. {
  169. Gost3410PublicKeyAlgParameters algParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
  170. Asn1OctetString key;
  171. try
  172. {
  173. key = (Asn1OctetString)keyInfo.ParsePublicKey();
  174. }
  175. catch (IOException e)
  176. {
  177. throw new ArgumentException("error recovering GOST3410_94 public key", e);
  178. }
  179. byte[] keyBytes = Arrays.Reverse(key.GetOctets()); // was little endian
  180. BigInteger y = new BigInteger(1, keyBytes);
  181. return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet);
  182. }
  183. else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
  184. {
  185. return new X25519PublicKeyParameters(GetRawKey(keyInfo));
  186. }
  187. else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
  188. {
  189. return new X448PublicKeyParameters(GetRawKey(keyInfo));
  190. }
  191. else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
  192. {
  193. return new Ed25519PublicKeyParameters(GetRawKey(keyInfo));
  194. }
  195. else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
  196. {
  197. return new Ed448PublicKeyParameters(GetRawKey(keyInfo));
  198. }
  199. else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256)
  200. || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512))
  201. {
  202. Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
  203. DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet;
  204. ECGost3410Parameters ecDomainParameters =new ECGost3410Parameters(
  205. new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOidX9(publicKeyParamSet)),
  206. publicKeyParamSet,
  207. gostParams.DigestParamSet,
  208. gostParams.EncryptionParamSet);
  209. Asn1OctetString key;
  210. try
  211. {
  212. key = (Asn1OctetString)keyInfo.ParsePublicKey();
  213. }
  214. catch (IOException e)
  215. {
  216. throw new ArgumentException("error recovering GOST3410_2012 public key", e);
  217. }
  218. int fieldSize = 32;
  219. if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512))
  220. {
  221. fieldSize = 64;
  222. }
  223. int keySize = 2 * fieldSize;
  224. byte[] keyEnc = key.GetOctets();
  225. if (keyEnc.Length != keySize)
  226. throw new ArgumentException("invalid length for GOST3410_2012 public key");
  227. byte[] x9Encoding = new byte[1 + keySize];
  228. x9Encoding[0] = 0x04;
  229. for (int i = 1; i <= fieldSize; ++i)
  230. {
  231. x9Encoding[i] = keyEnc[fieldSize - i];
  232. x9Encoding[i + fieldSize] = keyEnc[keySize - i];
  233. }
  234. ECPoint q = ecDomainParameters.Curve.DecodePoint(x9Encoding);
  235. return new ECPublicKeyParameters(q, ecDomainParameters);
  236. }
  237. else
  238. {
  239. throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid);
  240. }
  241. }
  242. private static byte[] GetRawKey(SubjectPublicKeyInfo keyInfo)
  243. {
  244. /*
  245. * TODO[RFC 8422]
  246. * - Require keyInfo.Algorithm.Parameters == null?
  247. */
  248. return keyInfo.PublicKeyData.GetOctets();
  249. }
  250. private static bool IsPkcsDHParam(Asn1Sequence seq)
  251. {
  252. if (seq.Count == 2)
  253. return true;
  254. if (seq.Count > 3)
  255. return false;
  256. DerInteger l = DerInteger.GetInstance(seq[2]);
  257. DerInteger p = DerInteger.GetInstance(seq[0]);
  258. return l.Value.CompareTo(BigInteger.ValueOf(p.Value.BitLength)) <= 0;
  259. }
  260. private static DHPublicKeyParameters ReadPkcsDHParam(DerObjectIdentifier algOid,
  261. BigInteger y, Asn1Sequence seq)
  262. {
  263. DHParameter para = new DHParameter(seq);
  264. BigInteger lVal = para.L;
  265. int l = lVal == null ? 0 : lVal.IntValue;
  266. DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
  267. return new DHPublicKeyParameters(y, dhParams, algOid);
  268. }
  269. }
  270. }
  271. #pragma warning restore
  272. #endif