util.d 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. module secured.util;
  2. import std.stdio;
  3. import secured.openssl;
  4. public enum uint FILE_BUFFER_SIZE = 32768;
  5. @trusted public class CryptographicException : Exception
  6. {
  7. this(string message)
  8. {
  9. super(message);
  10. debug {
  11. while(ERR_peek_error() != 0) {
  12. char[] buf = new char[512];
  13. ERR_error_string_n(ERR_get_error(), buf.ptr, 512);
  14. writeln(buf);
  15. }
  16. }
  17. }
  18. }
  19. @safe pure public bool constantTimeEquality(const ubyte[] a, const ubyte[] b)
  20. {
  21. if(a.length != b.length)
  22. return false;
  23. int result = 0;
  24. for(int i = 0; i < a.length; i++)
  25. result |= a[i] ^ b[i];
  26. return result == 0;
  27. }
  28. unittest
  29. {
  30. import std.digest;
  31. import std.stdio;
  32. import secured.random;
  33. writeln("Testing Constant Time Equality:");
  34. //Test random data
  35. ubyte[] rnd1 = random(32);
  36. ubyte[] rnd2 = random(32);
  37. writeln("Testing with Random Data");
  38. assert(!constantTimeEquality(rnd1, rnd2));
  39. //Test equal data
  40. ubyte[48] key1 = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  41. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  42. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  43. ubyte[48] key2 = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  44. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  45. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  46. writeln("Testing with Equal Data");
  47. assert(constantTimeEquality(key1, key2));
  48. }