FpeFf1Engine.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  7. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Fpe
  8. {
  9. public class FpeFf1Engine
  10. : FpeEngine
  11. {
  12. public FpeFf1Engine()
  13. : this(new AesEngine())
  14. {
  15. }
  16. public FpeFf1Engine(IBlockCipher baseCipher)
  17. : base(baseCipher)
  18. {
  19. if (IsOverrideSet(SP80038G.FPE_DISABLED) ||
  20. IsOverrideSet(SP80038G.FF1_DISABLED))
  21. {
  22. throw new InvalidOperationException("FF1 encryption disabled");
  23. }
  24. }
  25. public override void Init(bool forEncryption, ICipherParameters parameters)
  26. {
  27. this.forEncryption = forEncryption;
  28. this.fpeParameters = (FpeParameters)parameters;
  29. baseCipher.Init(!fpeParameters.UseInverseFunction, fpeParameters.Key);
  30. }
  31. protected override int EncryptBlock(byte[] inBuf, int inOff, int length, byte[] outBuf, int outOff)
  32. {
  33. byte[] enc;
  34. if (fpeParameters.Radix > 256)
  35. {
  36. if ((length & 1) != 0)
  37. throw new ArgumentException("input must be an even number of bytes for a wide radix");
  38. ushort[] u16In = Pack.BE_To_UInt16(inBuf, inOff, length);
  39. ushort[] u16Out = SP80038G.EncryptFF1w(baseCipher, fpeParameters.Radix, fpeParameters.GetTweak(),
  40. u16In, 0, u16In.Length);
  41. enc = Pack.UInt16_To_BE(u16Out, 0, u16Out.Length);
  42. }
  43. else
  44. {
  45. enc = SP80038G.EncryptFF1(baseCipher, fpeParameters.Radix, fpeParameters.GetTweak(), inBuf, inOff, length);
  46. }
  47. Array.Copy(enc, 0, outBuf, outOff, length);
  48. return length;
  49. }
  50. protected override int DecryptBlock(byte[] inBuf, int inOff, int length, byte[] outBuf, int outOff)
  51. {
  52. byte[] dec;
  53. if (fpeParameters.Radix > 256)
  54. {
  55. if ((length & 1) != 0)
  56. throw new ArgumentException("input must be an even number of bytes for a wide radix");
  57. ushort[] u16In = Pack.BE_To_UInt16(inBuf, inOff, length);
  58. ushort[] u16Out = SP80038G.DecryptFF1w(baseCipher, fpeParameters.Radix, fpeParameters.GetTweak(),
  59. u16In, 0, u16In.Length);
  60. dec = Pack.UInt16_To_BE(u16Out, 0, u16Out.Length);
  61. }
  62. else
  63. {
  64. dec = SP80038G.DecryptFF1(baseCipher, fpeParameters.Radix, fpeParameters.GetTweak(), inBuf, inOff, length);
  65. }
  66. Array.Copy(dec, 0, outBuf, outOff, length);
  67. return length;
  68. }
  69. }
  70. }
  71. #pragma warning restore
  72. #endif