BcTlsRsaSigner.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Encodings;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC
  11. {
  12. /// <summary>Operator supporting the generation of RSASSA-PKCS1-v1_5 signatures using the BC light-weight API.
  13. /// </summary>
  14. public class BcTlsRsaSigner
  15. : BcTlsSigner
  16. {
  17. private readonly RsaKeyParameters m_publicKey;
  18. public BcTlsRsaSigner(BcTlsCrypto crypto, RsaKeyParameters privateKey, RsaKeyParameters publicKey)
  19. : base(crypto, privateKey)
  20. {
  21. this.m_publicKey = publicKey;
  22. }
  23. public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash)
  24. {
  25. IDigest nullDigest = new NullDigest();
  26. ISigner signer;
  27. if (algorithm != null)
  28. {
  29. if (algorithm.Signature != SignatureAlgorithm.rsa)
  30. throw new InvalidOperationException("Invalid algorithm: " + algorithm);
  31. /*
  32. * RFC 5246 4.7. In RSA signing, the opaque vector contains the signature generated
  33. * using the RSASSA-PKCS1-v1_5 signature scheme defined in [PKCS1].
  34. */
  35. signer = new RsaDigestSigner(nullDigest, TlsUtilities.GetOidForHashAlgorithm(algorithm.Hash));
  36. }
  37. else
  38. {
  39. /*
  40. * RFC 5246 4.7. Note that earlier versions of TLS used a different RSA signature scheme
  41. * that did not include a DigestInfo encoding.
  42. */
  43. signer = new GenericSigner(new Pkcs1Encoding(new RsaBlindedEngine()), nullDigest);
  44. }
  45. signer.Init(true, new ParametersWithRandom(m_privateKey, m_crypto.SecureRandom));
  46. signer.BlockUpdate(hash, 0, hash.Length);
  47. try
  48. {
  49. byte[] signature = signer.GenerateSignature();
  50. signer.Init(false, m_publicKey);
  51. signer.BlockUpdate(hash, 0, hash.Length);
  52. if (signer.VerifySignature(signature))
  53. {
  54. return signature;
  55. }
  56. }
  57. catch (CryptoException e)
  58. {
  59. throw new TlsFatalAlert(AlertDescription.internal_error, e);
  60. }
  61. throw new TlsFatalAlert(AlertDescription.internal_error);
  62. }
  63. }
  64. }
  65. #pragma warning restore
  66. #endif