RsaDigestSigner.cs 7.5 KB

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