You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

StreamAesBouncyCastleEncryptor.cs 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Crypto.Engines;
  3. using Org.BouncyCastle.Crypto.Modes;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Security;
  6. using System;
  7. using System.Collections.Generic;
  8. namespace Shadowsocks.Encryption.Stream
  9. {
  10. public class StreamAesBouncyCastleEncryptor : StreamEncryptor
  11. {
  12. IBufferedCipher c;
  13. public StreamAesBouncyCastleEncryptor(string method, string password) : base(method, password)
  14. {
  15. c = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 128));
  16. // c = CipherUtilities.GetCipher("AES/CFB/NoPadding");
  17. }
  18. protected override void initCipher(byte[] iv, bool isEncrypt)
  19. {
  20. base.initCipher(iv, isEncrypt);
  21. c.Init(isEncrypt, new ParametersWithIV(new KeyParameter(key), iv));
  22. }
  23. protected override void cipherUpdate(bool isEncrypt, int length, byte[] buf, byte[] outbuf)
  24. {
  25. var i = buf.AsSpan().Slice(0, length);
  26. if (isEncrypt) CipherEncrypt(i, outbuf);
  27. else CipherDecrypt(outbuf, i);
  28. }
  29. protected override int CipherEncrypt(Span<byte> plain, Span<byte> cipher)
  30. {
  31. CipherUpdate(plain, cipher);
  32. return plain.Length;
  33. }
  34. protected override int CipherDecrypt(Span<byte> plain, Span<byte> cipher)
  35. {
  36. CipherUpdate(cipher, plain);
  37. return cipher.Length;
  38. }
  39. private void CipherUpdate(Span<byte> i, Span<byte> o)
  40. {
  41. var ob = new byte[o.Length];
  42. int blklen = c.ProcessBytes(i.ToArray(), 0, i.Length, ob, 0);
  43. int restlen = i.Length - blklen;
  44. if (restlen != 0)
  45. {
  46. c.DoFinal(ob, blklen);
  47. }
  48. ob.CopyTo(o);
  49. }
  50. #region Ciphers
  51. private static readonly Dictionary<string, CipherInfo> _ciphers = new Dictionary<string, CipherInfo>
  52. {
  53. {"aes-256-cfb",new CipherInfo("aes-256-cfb", 32, 16, CipherFamily.AesCfb, CipherStandardState.Unstable)},
  54. };
  55. public static Dictionary<string, CipherInfo> SupportedCiphers()
  56. {
  57. return _ciphers;
  58. }
  59. protected override Dictionary<string, CipherInfo> getCiphers()
  60. {
  61. return _ciphers;
  62. }
  63. #endregion
  64. }
  65. }