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.

SecretBox.cs 1.7 kB

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Discord.Audio
  4. {
  5. public unsafe static class SecretBox
  6. {
  7. [DllImport("libsodium", EntryPoint = "crypto_secretbox_easy", CallingConvention = CallingConvention.Cdecl)]
  8. private static extern int SecretBoxEasy(byte* output, byte* input, long inputLength, byte[] nonce, byte[] secret);
  9. [DllImport("libsodium", EntryPoint = "crypto_secretbox_open_easy", CallingConvention = CallingConvention.Cdecl)]
  10. private static extern int SecretBoxOpenEasy(byte* output, byte* input, long inputLength, byte[] nonce, byte[] secret);
  11. public static int Encrypt(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, byte[] nonce, byte[] secret)
  12. {
  13. fixed (byte* inPtr = input)
  14. fixed (byte* outPtr = output)
  15. {
  16. int error = SecretBoxEasy(outPtr + outputOffset, inPtr + inputOffset, inputLength, nonce, secret);
  17. if (error != 0)
  18. throw new Exception($"Sodium Error: {error}");
  19. return inputLength + 16;
  20. }
  21. }
  22. public static int Decrypt(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, byte[] nonce, byte[] secret)
  23. {
  24. fixed (byte* inPtr = input)
  25. fixed (byte* outPtr = output)
  26. {
  27. int error = SecretBoxOpenEasy(outPtr + outputOffset, inPtr + inputOffset, inputLength, nonce, secret);
  28. if (error != 0)
  29. throw new Exception($"Sodium Error: {error}");
  30. return inputLength - 16;
  31. }
  32. }
  33. }
  34. }