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.

StreamChachaNaClEncryptor.cs 1.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using NaCl.Core;
  4. namespace Shadowsocks.Encryption.Stream
  5. {
  6. public class StreamChachaNaClEncryptor : StreamEncryptor
  7. {
  8. readonly ChaCha20 c;
  9. public StreamChachaNaClEncryptor(string method, string password) : base(method, password)
  10. {
  11. c = new ChaCha20(key, 0);
  12. }
  13. protected override int CipherDecrypt(Span<byte> plain, Span<byte> cipher)
  14. {
  15. var p = c.Decrypt(cipher, iv);
  16. p.CopyTo(plain);
  17. return p.Length;
  18. }
  19. protected override int CipherEncrypt(Span<byte> plain, Span<byte> cipher)
  20. {
  21. var e = c.Encrypt(plain, iv);
  22. e.CopyTo(cipher);
  23. return e.Length;
  24. }
  25. protected override void cipherUpdate(bool isEncrypt, int length, byte[] buf, byte[] outbuf)
  26. {
  27. var i = buf.AsSpan().Slice(0, length);
  28. if (isEncrypt)
  29. {
  30. CipherEncrypt(i, outbuf);
  31. }
  32. else
  33. {
  34. CipherDecrypt(outbuf, i);
  35. }
  36. }
  37. #region Ciphers
  38. private static readonly Dictionary<string, CipherInfo> _ciphers = new Dictionary<string, CipherInfo>
  39. {
  40. { "chacha20-ietf", new CipherInfo("chacha20-ietf", 32, 12, CipherFamily.Chacha20) },
  41. };
  42. public static Dictionary<string, CipherInfo> SupportedCiphers()
  43. {
  44. return _ciphers;
  45. }
  46. protected override Dictionary<string, CipherInfo> getCiphers()
  47. {
  48. return _ciphers;
  49. }
  50. #endregion
  51. }
  52. }