RsaDigestSigner.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224;
  43. oidMap["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256;
  44. oidMap["SHA3-224"] = NistObjectIdentifiers.IdSha3_224;
  45. oidMap["SHA3-256"] = NistObjectIdentifiers.IdSha3_256;
  46. oidMap["SHA3-384"] = NistObjectIdentifiers.IdSha3_384;
  47. oidMap["SHA3-512"] = NistObjectIdentifiers.IdSha3_512;
  48. oidMap["MD2"] = PkcsObjectIdentifiers.MD2;
  49. oidMap["MD4"] = PkcsObjectIdentifiers.MD4;
  50. oidMap["MD5"] = PkcsObjectIdentifiers.MD5;
  51. }
  52. public RsaDigestSigner(IDigest digest)
  53. : this(digest, (DerObjectIdentifier)oidMap[digest.AlgorithmName])
  54. {
  55. }
  56. public RsaDigestSigner(IDigest digest, DerObjectIdentifier digestOid)
  57. : this(digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
  58. {
  59. }
  60. public RsaDigestSigner(IDigest digest, AlgorithmIdentifier algId)
  61. : this(new RsaCoreEngine(), digest, algId)
  62. {
  63. }
  64. public RsaDigestSigner(IRsa rsa, IDigest digest, DerObjectIdentifier digestOid)
  65. : this(rsa, digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
  66. {
  67. }
  68. public RsaDigestSigner(IRsa rsa, IDigest digest, AlgorithmIdentifier algId)
  69. : this(new RsaBlindedEngine(rsa), digest, algId)
  70. {
  71. }
  72. public RsaDigestSigner(IAsymmetricBlockCipher rsaEngine, IDigest digest, AlgorithmIdentifier algId)
  73. {
  74. this.rsaEngine = new Pkcs1Encoding(rsaEngine);
  75. this.digest = digest;
  76. this.algId = algId;
  77. }
  78. public virtual string AlgorithmName
  79. {
  80. get { return digest.AlgorithmName + "withRSA"; }
  81. }
  82. /**
  83. * Initialise the signer for signing or verification.
  84. *
  85. * @param forSigning true if for signing, false otherwise
  86. * @param param necessary parameters.
  87. */
  88. public virtual void Init(
  89. bool forSigning,
  90. ICipherParameters parameters)
  91. {
  92. this.forSigning = forSigning;
  93. AsymmetricKeyParameter k;
  94. if (parameters is ParametersWithRandom)
  95. {
  96. k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
  97. }
  98. else
  99. {
  100. k = (AsymmetricKeyParameter)parameters;
  101. }
  102. if (forSigning && !k.IsPrivate)
  103. throw new InvalidKeyException("Signing requires private key.");
  104. if (!forSigning && k.IsPrivate)
  105. throw new InvalidKeyException("Verification requires public key.");
  106. Reset();
  107. rsaEngine.Init(forSigning, parameters);
  108. }
  109. /**
  110. * update the internal digest with the byte b
  111. */
  112. public virtual void Update(
  113. byte input)
  114. {
  115. digest.Update(input);
  116. }
  117. /**
  118. * update the internal digest with the byte array in
  119. */
  120. public virtual void BlockUpdate(
  121. byte[] input,
  122. int inOff,
  123. int length)
  124. {
  125. digest.BlockUpdate(input, inOff, length);
  126. }
  127. /**
  128. * Generate a signature for the message we've been loaded with using
  129. * the key we were initialised with.
  130. */
  131. public virtual byte[] GenerateSignature()
  132. {
  133. if (!forSigning)
  134. throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");
  135. byte[] hash = new byte[digest.GetDigestSize()];
  136. digest.DoFinal(hash, 0);
  137. byte[] data = DerEncode(hash);
  138. return rsaEngine.ProcessBlock(data, 0, data.Length);
  139. }
  140. /**
  141. * return true if the internal state represents the signature described
  142. * in the passed in array.
  143. */
  144. public virtual bool VerifySignature(
  145. byte[] signature)
  146. {
  147. if (forSigning)
  148. throw new InvalidOperationException("RsaDigestSigner not initialised for verification");
  149. byte[] hash = new byte[digest.GetDigestSize()];
  150. digest.DoFinal(hash, 0);
  151. byte[] sig;
  152. byte[] expected;
  153. try
  154. {
  155. sig = rsaEngine.ProcessBlock(signature, 0, signature.Length);
  156. expected = DerEncode(hash);
  157. }
  158. catch (Exception)
  159. {
  160. return false;
  161. }
  162. if (sig.Length == expected.Length)
  163. {
  164. return Arrays.ConstantTimeAreEqual(sig, expected);
  165. }
  166. else if (sig.Length == expected.Length - 2) // NULL left out
  167. {
  168. int sigOffset = sig.Length - hash.Length - 2;
  169. int expectedOffset = expected.Length - hash.Length - 2;
  170. expected[1] -= 2; // adjust lengths
  171. expected[3] -= 2;
  172. int nonEqual = 0;
  173. for (int i = 0; i < hash.Length; i++)
  174. {
  175. nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]);
  176. }
  177. for (int i = 0; i < sigOffset; i++)
  178. {
  179. nonEqual |= (sig[i] ^ expected[i]); // check header less NULL
  180. }
  181. return nonEqual == 0;
  182. }
  183. else
  184. {
  185. return false;
  186. }
  187. }
  188. public virtual void Reset()
  189. {
  190. digest.Reset();
  191. }
  192. private byte[] DerEncode(byte[] hash)
  193. {
  194. if (algId == null)
  195. {
  196. // For raw RSA, the DigestInfo must be prepared externally
  197. return hash;
  198. }
  199. DigestInfo dInfo = new DigestInfo(algId, hash);
  200. return dInfo.GetDerEncoded();
  201. }
  202. }
  203. }
  204. #pragma warning restore
  205. #endif