FpeFf1Engine.cs 2.9 KB

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