RsaDigestSigner.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  10. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Encodings;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  13. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  14. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  15. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
  16. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  17. {
  18. public class RsaDigestSigner
  19. : ISigner
  20. {
  21. private readonly IAsymmetricBlockCipher rsaEngine;
  22. private readonly AlgorithmIdentifier algId;
  23. private readonly IDigest digest;
  24. private bool forSigning;
  25. private static readonly IDictionary<string, DerObjectIdentifier> OidMap =
  26. new Dictionary<string, DerObjectIdentifier>(StringComparer.OrdinalIgnoreCase);
  27. /// <summary>
  28. /// Load oid table.
  29. /// </summary>
  30. static RsaDigestSigner()
  31. {
  32. OidMap["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128;
  33. OidMap["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160;
  34. OidMap["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256;
  35. OidMap["SHA-1"] = X509ObjectIdentifiers.IdSha1;
  36. OidMap["SHA-224"] = NistObjectIdentifiers.IdSha224;
  37. OidMap["SHA-256"] = NistObjectIdentifiers.IdSha256;
  38. OidMap["SHA-384"] = NistObjectIdentifiers.IdSha384;
  39. OidMap["SHA-512"] = NistObjectIdentifiers.IdSha512;
  40. OidMap["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224;
  41. OidMap["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256;
  42. OidMap["SHA3-224"] = NistObjectIdentifiers.IdSha3_224;
  43. OidMap["SHA3-256"] = NistObjectIdentifiers.IdSha3_256;
  44. OidMap["SHA3-384"] = NistObjectIdentifiers.IdSha3_384;
  45. OidMap["SHA3-512"] = NistObjectIdentifiers.IdSha3_512;
  46. OidMap["MD2"] = PkcsObjectIdentifiers.MD2;
  47. OidMap["MD4"] = PkcsObjectIdentifiers.MD4;
  48. OidMap["MD5"] = PkcsObjectIdentifiers.MD5;
  49. }
  50. public RsaDigestSigner(IDigest digest)
  51. : this(digest, CollectionUtilities.GetValueOrNull(OidMap, digest.AlgorithmName))
  52. {
  53. }
  54. public RsaDigestSigner(IDigest digest, DerObjectIdentifier digestOid)
  55. : this(digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
  56. {
  57. }
  58. public RsaDigestSigner(IDigest digest, AlgorithmIdentifier algId)
  59. : this(new RsaCoreEngine(), digest, algId)
  60. {
  61. }
  62. public RsaDigestSigner(IRsa rsa, IDigest digest, DerObjectIdentifier digestOid)
  63. : this(rsa, digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
  64. {
  65. }
  66. public RsaDigestSigner(IRsa rsa, IDigest digest, AlgorithmIdentifier algId)
  67. : this(new RsaBlindedEngine(rsa), digest, algId)
  68. {
  69. }
  70. public RsaDigestSigner(IAsymmetricBlockCipher rsaEngine, IDigest digest, AlgorithmIdentifier algId)
  71. {
  72. this.rsaEngine = new Pkcs1Encoding(rsaEngine);
  73. this.digest = digest;
  74. this.algId = algId;
  75. }
  76. public virtual string AlgorithmName
  77. {
  78. get { return digest.AlgorithmName + "withRSA"; }
  79. }
  80. /**
  81. * Initialise the signer for signing or verification.
  82. *
  83. * @param forSigning true if for signing, false otherwise
  84. * @param param necessary parameters.
  85. */
  86. public virtual void Init(
  87. bool forSigning,
  88. ICipherParameters parameters)
  89. {
  90. this.forSigning = forSigning;
  91. AsymmetricKeyParameter k;
  92. if (parameters is ParametersWithRandom)
  93. {
  94. k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
  95. }
  96. else
  97. {
  98. k = (AsymmetricKeyParameter)parameters;
  99. }
  100. if (forSigning && !k.IsPrivate)
  101. throw new InvalidKeyException("Signing requires private key.");
  102. if (!forSigning && k.IsPrivate)
  103. throw new InvalidKeyException("Verification requires public key.");
  104. Reset();
  105. rsaEngine.Init(forSigning, parameters);
  106. }
  107. public virtual void Update(byte input)
  108. {
  109. digest.Update(input);
  110. }
  111. public virtual void BlockUpdate(byte[] input, int inOff, int inLen)
  112. {
  113. digest.BlockUpdate(input, inOff, inLen);
  114. }
  115. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  116. public virtual void BlockUpdate(ReadOnlySpan<byte> input)
  117. {
  118. digest.BlockUpdate(input);
  119. }
  120. #endif
  121. public virtual byte[] GenerateSignature()
  122. {
  123. if (!forSigning)
  124. throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");
  125. byte[] hash = new byte[digest.GetDigestSize()];
  126. digest.DoFinal(hash, 0);
  127. byte[] data = DerEncode(hash);
  128. return rsaEngine.ProcessBlock(data, 0, data.Length);
  129. }
  130. public virtual bool VerifySignature(byte[] signature)
  131. {
  132. if (forSigning)
  133. throw new InvalidOperationException("RsaDigestSigner not initialised for verification");
  134. byte[] hash = new byte[digest.GetDigestSize()];
  135. digest.DoFinal(hash, 0);
  136. byte[] sig;
  137. byte[] expected;
  138. try
  139. {
  140. sig = rsaEngine.ProcessBlock(signature, 0, signature.Length);
  141. expected = DerEncode(hash);
  142. }
  143. catch (Exception)
  144. {
  145. return false;
  146. }
  147. if (sig.Length == expected.Length)
  148. {
  149. return Arrays.ConstantTimeAreEqual(sig, expected);
  150. }
  151. else if (sig.Length == expected.Length - 2) // NULL left out
  152. {
  153. int sigOffset = sig.Length - hash.Length - 2;
  154. int expectedOffset = expected.Length - hash.Length - 2;
  155. expected[1] -= 2; // adjust lengths
  156. expected[3] -= 2;
  157. int nonEqual = 0;
  158. for (int i = 0; i < hash.Length; i++)
  159. {
  160. nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]);
  161. }
  162. for (int i = 0; i < sigOffset; i++)
  163. {
  164. nonEqual |= (sig[i] ^ expected[i]); // check header less NULL
  165. }
  166. return nonEqual == 0;
  167. }
  168. else
  169. {
  170. return false;
  171. }
  172. }
  173. public virtual void Reset()
  174. {
  175. digest.Reset();
  176. }
  177. private byte[] DerEncode(byte[] hash)
  178. {
  179. if (algId == null)
  180. {
  181. // For raw RSA, the DigestInfo must be prepared externally
  182. return hash;
  183. }
  184. DigestInfo dInfo = new DigestInfo(algId, hash);
  185. return dInfo.GetDerEncoded();
  186. }
  187. }
  188. }
  189. #pragma warning restore
  190. #endif