kdf.d 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. module secured.kdf;
  2. import std.base64;
  3. import std.conv;
  4. import std.typecons;
  5. import std.format;
  6. import std.string;
  7. import deimos.openssl.evp;
  8. import deimos.openssl.kdf;
  9. import secured.openssl;
  10. import secured.hash;
  11. import secured.random;
  12. import secured.symmetric;
  13. import secured.util;
  14. public enum uint defaultKdfIterations = 1_048_576;
  15. public enum ushort defaultSCryptR = 8;
  16. public enum ushort defaultSCryptP = 1;
  17. public enum ulong maxSCryptMemory = 1_074_790_400;
  18. public enum KdfAlgorithm : ubyte {
  19. None = 0,
  20. PBKDF2 = 1,
  21. HKDF = 2,
  22. SCrypt = 3,
  23. Argon2 = 4,
  24. Default = SCrypt,
  25. }
  26. public enum VerifyPasswordResult
  27. {
  28. /// <summary>
  29. /// The password verification was successful.
  30. /// </summary>
  31. Success,
  32. /// <summary>
  33. /// The password verification failed.
  34. /// </summary>
  35. Failure,
  36. /// <summary>
  37. /// The password was successfully verified, but needs to be rehashed to use updated hashing parameters.
  38. /// </summary>
  39. Rehash,
  40. }
  41. @safe public struct HashedPassword
  42. {
  43. /// <summary>
  44. /// The hashing algorithm used to secure the password.
  45. /// </summary>
  46. public KdfAlgorithm algorithm;
  47. /// <summary>
  48. /// The version of the hash parameters used to secure the password.
  49. /// </summary>
  50. public short parameterVersion;
  51. /// <summary>
  52. /// The salt used by the hashing function.
  53. /// </summary>
  54. public ubyte[] salt;
  55. /// <summary>
  56. /// The hashed password
  57. /// </summary>
  58. public ubyte[] derived;
  59. /// <summary>
  60. /// Constructs a HashedPassword object from the provided hashing parameters.
  61. /// </summary>
  62. /// <param name="derived">The hashed password.</param>
  63. /// <param name="salt">The salt used by the hashing function.</param>
  64. /// <param name="algorithm">The hashing algorithm used to secure the password.</param>
  65. /// <param name="paramVersion">The version of the hash parameters used to secure the password.</param>
  66. package this(ubyte[] derived, ubyte[] salt, KdfAlgorithm algorithm, ushort paramVersion)
  67. {
  68. this.algorithm = algorithm;
  69. this.parameterVersion = paramVersion;
  70. this.salt = salt;
  71. this.derived = derived;
  72. }
  73. /// <summary>
  74. /// Constructs a HashedPassword from an encoded string.
  75. /// </summary>
  76. /// <param name="encoded">The encoded string.</param>
  77. /// <returns>A HashedPassword object containing the decoded string values.</returns>
  78. /// <exception cref="ArgumentOutOfRangeException">The provided string is invalid.</exception>
  79. public this(string encoded) {
  80. auto parts = encoded.split(".");
  81. if (parts.length != 4) throw new CryptographicException("Invalid password string provided.");
  82. this.algorithm = to!KdfAlgorithm(to!int(parts[0]));
  83. this.parameterVersion = to!ushort(parts[1]);
  84. this.salt = Base64.decode(parts[2]);
  85. this.derived = Base64.decode(parts[3]);
  86. }
  87. /// <summary>
  88. /// Creates string containing the encoded password from the HashedPassword.
  89. /// </summary>
  90. /// <returns>The encoded password string</returns>
  91. public string toString() {
  92. return to!string(join([to!string(to!int(algorithm)), to!string(parameterVersion), Base64.encode(salt), Base64.encode(derived)], "."));
  93. }
  94. }
  95. @safe public HashedPassword securePassword(string password, const ubyte[] pepper, KdfAlgorithm algorithm = KdfAlgorithm.Default) {
  96. if (algorithm == KdfAlgorithm.HKDF) throw new CryptographicException("KdfAlgorithm.HKDF is not supported for password security.");
  97. if (algorithm == KdfAlgorithm.PBKDF2) {
  98. ubyte[] salt = random(32);
  99. return HashedPassword(pbkdf2_ex(password, salt ~ pepper, HashAlgorithm.Default, 64, defaultKdfIterations), salt, algorithm, 1);
  100. }
  101. if (algorithm == KdfAlgorithm.SCrypt) {
  102. ubyte[] salt = random(32);
  103. return HashedPassword(scrypt_ex(password, salt ~ pepper, 64), salt, algorithm, 1);
  104. }
  105. if (algorithm == KdfAlgorithm.Argon2) throw new CryptographicException("Argon2 is not supported.");
  106. throw new CryptographicException("KdfAlgorithm.None is not supported for password security.");
  107. }
  108. @safe public VerifyPasswordResult verifyPassword(string suppliedPassword, HashedPassword storedPassword, const ubyte[] pepper) {
  109. if (storedPassword.algorithm == KdfAlgorithm.HKDF) throw new CryptographicException("KdfAlgorithm.HKDF is not supported for password security.");
  110. if (storedPassword.algorithm == KdfAlgorithm.PBKDF2 && storedPassword.parameterVersion == 1) {
  111. if (pbkdf2_verify_ex(storedPassword.derived, suppliedPassword, storedPassword.salt ~ pepper, HashAlgorithm.Default, 64, defaultKdfIterations)) return VerifyPasswordResult.Success;
  112. }
  113. else if (storedPassword.algorithm == KdfAlgorithm.PBKDF2 && storedPassword.parameterVersion == 0) {
  114. if (pbkdf2_verify_ex(storedPassword.derived, suppliedPassword, storedPassword.salt ~ pepper, HashAlgorithm.SHA2_512, to!uint(storedPassword.derived.length), 100000)) return VerifyPasswordResult.Rehash;
  115. }
  116. if (storedPassword.algorithm == KdfAlgorithm.SCrypt && storedPassword.parameterVersion == 1) {
  117. ubyte[] supplied = scrypt_ex(suppliedPassword, storedPassword.salt ~ pepper, 64);
  118. if (supplied.constantTimeEquality(storedPassword.derived)) return VerifyPasswordResult.Success;
  119. }
  120. if (storedPassword.algorithm == KdfAlgorithm.Argon2) throw new CryptographicException("Argon2 is not supported.");
  121. return VerifyPasswordResult.Failure;
  122. }
  123. unittest {
  124. import std.digest;
  125. import std.stdio;
  126. ubyte[48] salt = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  127. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  128. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  129. writeln("Successful Password Test");
  130. HashedPassword successTest = securePassword("TestPassword!@#$%", salt);
  131. writeln("Encoded: ", successTest.toString());
  132. auto verifyResult = verifyPassword("TestPassword!@#$%", successTest, salt);
  133. assert (verifyResult == VerifyPasswordResult.Success);
  134. writeln("Failure Password Test");
  135. HashedPassword failTest = securePassword("TestPassword!@#$%", salt);
  136. writeln("Encoded: ", failTest.toString());
  137. verifyResult = verifyPassword("TestPassword!@#$", failTest, salt);
  138. assert (verifyResult == VerifyPasswordResult.Failure);
  139. writeln("PBKDF2 Password Test");
  140. HashedPassword pbkdf2Test = securePassword("TestPassword!@#$%", salt, KdfAlgorithm.PBKDF2);
  141. writeln("Encoded: ", pbkdf2Test.toString());
  142. verifyResult = verifyPassword("TestPassword!@#$%", pbkdf2Test, salt);
  143. assert (verifyResult == VerifyPasswordResult.Success);
  144. }
  145. public struct KdfResult {
  146. public ubyte[] salt;
  147. public ubyte[] key;
  148. }
  149. @safe public KdfResult pbkdf2(string password, uint iterations = defaultKdfIterations) {
  150. KdfResult result;
  151. result.salt = random(getHashLength(HashAlgorithm.Default));
  152. result.key = pbkdf2_ex(password, result.salt, HashAlgorithm.Default, getHashLength(HashAlgorithm.Default), iterations);
  153. return result;
  154. }
  155. @safe public bool pbkdf2_verify(const ubyte[] key, const ubyte[] salt, string password, uint iterations = defaultKdfIterations) {
  156. ubyte[] test = pbkdf2_ex(password, salt, HashAlgorithm.Default, getHashLength(HashAlgorithm.Default), iterations);
  157. return constantTimeEquality(key, test);
  158. }
  159. @trusted public ubyte[] pbkdf2_ex(string password, const ubyte[] salt, HashAlgorithm func, uint outputLen, uint iterations) {
  160. ubyte[] output = new ubyte[outputLen];
  161. if(PKCS5_PBKDF2_HMAC(password.ptr, cast(int)password.length, salt.ptr, cast(int)salt.length, iterations, getOpenSSLHashAlgorithm(func), outputLen, output.ptr) == 0) {
  162. throw new CryptographicException("Unable to execute PBKDF2 hash function.");
  163. }
  164. return output;
  165. }
  166. @safe public bool pbkdf2_verify_ex(const ubyte[] test, string password, const ubyte[] salt, HashAlgorithm func, uint outputLen, uint iterations) {
  167. ubyte[] key = pbkdf2_ex(password, salt, func, outputLen, iterations);
  168. return constantTimeEquality(test, key);
  169. }
  170. unittest
  171. {
  172. import std.datetime.stopwatch;
  173. import std.digest;
  174. import std.stdio;
  175. writeln("Testing PBKDF2 Basic Methods:");
  176. //Test basic methods
  177. auto sw = StopWatch(AutoStart.no);
  178. sw.start();
  179. auto result = pbkdf2("password");
  180. sw.stop();
  181. writefln("PBKDF2 took %sms for 1,000,000 iterations", sw.peek.total!"msecs");
  182. assert(result.key.length == 48);
  183. assert(pbkdf2_verify(result.key, result.salt, "password"));
  184. writeln(toHexString!(LetterCase.lower)(result.key));
  185. //Test extended methods
  186. ubyte[32] salt = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  187. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  188. ubyte[] key = pbkdf2_ex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", salt, HashAlgorithm.SHA2_384, 64, 100000);
  189. assert(pbkdf2_verify_ex(key, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", salt, HashAlgorithm.SHA2_384, 64, 100000));
  190. writeln(toHexString!(LetterCase.lower)(key));
  191. }
  192. unittest
  193. {
  194. import std.digest;
  195. import std.stdio;
  196. writeln("Testing PBKDF2 Extended with Defaults:");
  197. ubyte[48] key = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  198. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  199. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  200. ubyte[] vec1 = pbkdf2_ex("", key, HashAlgorithm.SHA2_384, 48, 25000);
  201. ubyte[] vec2 = pbkdf2_ex("abc", key, HashAlgorithm.SHA2_384, 48, 25000);
  202. ubyte[] vec3 = pbkdf2_ex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", key, HashAlgorithm.SHA2_384, 48, 25000);
  203. writeln(toHexString!(LetterCase.lower)(vec1));
  204. writeln(toHexString!(LetterCase.lower)(vec2));
  205. writeln(toHexString!(LetterCase.lower)(vec3));
  206. assert(toHexString!(LetterCase.lower)(vec1) == "b0ddf56b90903d638ec8d07a4205ba2bcfa944955d553e1ef3f91cba84e8e3bde9db7c8ccf14df26f8305fc8634572f9");
  207. assert(toHexString!(LetterCase.lower)(vec2) == "b0a5e09a38bee3eb2b84d477d5259ef7bebf0e48d9512178f7e26cc330278ff45417d47d84db06a12b8ea49377a7c7cb");
  208. assert(toHexString!(LetterCase.lower)(vec3) == "d1aacafea3a9fdf3ee6236b1b45527974ea01539b4a7cc493bba56e15e14d520b2834d7bf22b83bb5c21c4bccb423be2");
  209. }
  210. unittest
  211. {
  212. import std.digest;
  213. import std.stdio;
  214. writeln("Testing PBKDF2 Extended with Custom Iterations:");
  215. ubyte[48] key = [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  216. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  217. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  218. ubyte[] vec1 = pbkdf2_ex("", key, HashAlgorithm.SHA2_384, 48, 150000);
  219. ubyte[] vec2 = pbkdf2_ex("abc", key, HashAlgorithm.SHA2_384, 48, 150000);
  220. ubyte[] vec3 = pbkdf2_ex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", key, HashAlgorithm.SHA2_384, 48, 150000);
  221. writeln(toHexString!(LetterCase.lower)(vec1));
  222. writeln(toHexString!(LetterCase.lower)(vec2));
  223. writeln(toHexString!(LetterCase.lower)(vec3));
  224. assert(toHexString!(LetterCase.lower)(vec1) == "babdcbbf4ff89367ed223d2edd06ef5473ac9cdc827783ed0b4b5eafd9e4097beb2ef66d6fc92d24dbf4b86aa51b4a0f");
  225. assert(toHexString!(LetterCase.lower)(vec2) == "8894348ccea06d79f80382ae7d4434c0f2ef41f871d936604f426518ab23bde4410fddce6dad943c95de75dbece9b54a");
  226. assert(toHexString!(LetterCase.lower)(vec3) == "fba55e91818c35b1e4cc753fbd01a6cd138c49da472b58b2d7c4860ba39a3dd9032f8f641aadcd74a819361ed27c9a0f");
  227. }
  228. unittest
  229. {
  230. import std.digest;
  231. import std.stdio;
  232. writeln("Testing PBKDF2 Extended with Custom Output Length:");
  233. ubyte[48] key = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  234. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  235. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  236. ubyte[] vec1 = pbkdf2_ex("", key, HashAlgorithm.SHA2_384, 32, 25000);
  237. ubyte[] vec2 = pbkdf2_ex("abc", key, HashAlgorithm.SHA2_384, 32, 25000);
  238. ubyte[] vec3 = pbkdf2_ex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", key, HashAlgorithm.SHA2_384, 32, 25000);
  239. writeln(toHexString!(LetterCase.lower)(vec1));
  240. writeln(toHexString!(LetterCase.lower)(vec2));
  241. writeln(toHexString!(LetterCase.lower)(vec3));
  242. assert(toHexString!(LetterCase.lower)(vec1) == "b0ddf56b90903d638ec8d07a4205ba2bcfa944955d553e1ef3f91cba84e8e3bd");
  243. assert(toHexString!(LetterCase.lower)(vec2) == "b0a5e09a38bee3eb2b84d477d5259ef7bebf0e48d9512178f7e26cc330278ff4");
  244. assert(toHexString!(LetterCase.lower)(vec3) == "d1aacafea3a9fdf3ee6236b1b45527974ea01539b4a7cc493bba56e15e14d520");
  245. }
  246. @safe public KdfResult hkdf(const SymmetricKey key) {
  247. return hkdf(key, getCipherKeyLength(key.algorithm));
  248. }
  249. @safe public KdfResult hkdf(const SymmetricKey key, size_t outputLen) {
  250. KdfResult result;
  251. result.salt = random(getHashLength(HashAlgorithm.Default));
  252. result.key = hkdf_ex(key.value, result.salt, string.init, outputLen, HashAlgorithm.Default);
  253. return result;
  254. }
  255. @trusted public ubyte[] hkdf_ex(const ubyte[] key, const ubyte[] salt, string info, size_t outputLen, HashAlgorithm func) {
  256. if (key.length == 0) {
  257. throw new CryptographicException("HKDF key cannot be an empty array.");
  258. }
  259. EVP_KDF *kdf;
  260. EVP_KDF_CTX *kctx = null;
  261. ubyte[] derived = new ubyte[outputLen];
  262. ossl_param_st[5] params;
  263. /* Find and allocate a context for the HKDF algorithm */
  264. if ((kdf = EVP_KDF_fetch(null, "hkdf", null)) == null) {
  265. throw new CryptographicException("Unable to create HKDF function.");
  266. }
  267. kctx = EVP_KDF_CTX_new(kdf);
  268. scope(exit) {
  269. if (kctx !is null) {
  270. EVP_KDF_CTX_free(kctx);
  271. }
  272. }
  273. /* Build up the parameters for the derivation */
  274. string hashName = getOpenSSLHashAlgorithmString(func);
  275. params[0] = OSSL_PARAM_construct_utf8_string("digest".toStringz(), cast(char*)hashName.toStringz(), hashName.length+1);
  276. params[1] = OSSL_PARAM_construct_octet_string("salt".toStringz(), cast(void*)salt, salt.length);
  277. params[2] = OSSL_PARAM_construct_octet_string("key".toStringz(), cast(void*)key, key.length);
  278. params[3] = OSSL_PARAM_construct_octet_string("info".toStringz(), cast(void*)info, info.length);
  279. params[4] = OSSL_PARAM_construct_end();
  280. if (EVP_KDF_CTX_set_params(kctx, params.ptr) <= 0) {
  281. throw new CryptographicException("Unable to set the HKDF parameters.");
  282. }
  283. /* Do the derivation */
  284. if (EVP_KDF_derive(kctx, derived.ptr, outputLen, null) <= 0) {
  285. throw new CryptographicException("Unable to generate the requested key material.");
  286. }
  287. return derived;
  288. }
  289. unittest
  290. {
  291. import std.digest;
  292. import std.stdio;
  293. writeln("Testing HKDF Extended with Defaults:");
  294. ubyte[48] salt = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  295. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  296. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  297. ubyte[] vec2 = hkdf_ex(cast(ubyte[])"abc", salt, "", 64, HashAlgorithm.SHA2_384);
  298. ubyte[] vec3 = hkdf_ex(cast(ubyte[])"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", salt, "test", 64, HashAlgorithm.SHA2_384);
  299. writeln(toHexString!(LetterCase.lower)(vec2));
  300. writeln(toHexString!(LetterCase.lower)(vec3));
  301. assert(toHexString!(LetterCase.lower)(vec2) == "65e464a5d7026678a3af78bf0282592472f85ccd7d1040e2dea5cea9218276a960367d418154a1e95019182a3c857286860aa0711955829e896b5bcdb1224794");
  302. assert(toHexString!(LetterCase.lower)(vec3) == "12a82466f85ead03f50bb502475b47ec50e7224a90f0219955bf09846ed72791206f6e713a529a0082bf7229093f2b4e6c6b467119518a2579a5b091ebe8ba12");
  303. }
  304. unittest
  305. {
  306. import std.digest;
  307. import std.stdio;
  308. writeln("Testing HKDF Extended with SHA3_384:");
  309. ubyte[48] salt = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  310. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  311. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  312. ubyte[] vec2 = hkdf_ex(cast(ubyte[])"abc", salt, "", 64, HashAlgorithm.SHA3_384);
  313. ubyte[] vec3 = hkdf_ex(cast(ubyte[])"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", salt, "test", 64, HashAlgorithm.SHA3_384);
  314. writeln(toHexString!(LetterCase.lower)(vec2));
  315. writeln(toHexString!(LetterCase.lower)(vec3));
  316. assert(toHexString!(LetterCase.lower)(vec2) == "41999e49a273f7f1367c7b3c7bd80d56fa27307cdfdf0274c022a0185080ddaa36410a93098f325785e5c27c406df535c91cc47096dc846d5c1dea671a40f944");
  317. assert(toHexString!(LetterCase.lower)(vec3) == "15addd263fdab613056a7a82804c1d1c158ea901424d277c25407c15be4b7aa8cad52251de18b3151145035e94c8f360517bda7912d2249f80c9662c1a1cd345");
  318. }
  319. @safe public KdfResult scrypt(string password) {
  320. KdfResult result;
  321. result.salt = random(32);
  322. result.key = scrypt_ex(password, result.salt, defaultSCryptR, defaultSCryptR, defaultSCryptP, maxSCryptMemory, 64);
  323. return result;
  324. }
  325. @safe public KdfResult scrypt(const ubyte[] password) {
  326. KdfResult result;
  327. result.salt = random(32);
  328. result.key = scrypt_ex(password, result.salt, defaultKdfIterations, defaultSCryptR, defaultSCryptP, maxSCryptMemory, 64);
  329. return result;
  330. }
  331. @trusted public ubyte[] scrypt_ex(string password, const ubyte[] salt, size_t length) {
  332. return scrypt_ex(cast(ubyte[])password, salt, defaultKdfIterations, defaultSCryptR, defaultSCryptP, maxSCryptMemory, length);
  333. }
  334. @trusted public ubyte[] scrypt_ex(string password, const ubyte[] salt, ulong n, ulong r, ulong p, ulong maxMemory, size_t length) {
  335. import std.string;
  336. return scrypt_ex(cast(ubyte[])password.representation, salt, n, r, p, maxMemory, length);
  337. }
  338. @trusted public ubyte[] scrypt_ex(const ubyte[] password, const ubyte[] salt, ulong n, ulong r, ulong p, ulong maxMemory, size_t length) {
  339. ubyte[] hash = new ubyte[length];
  340. if (EVP_PBE_scrypt((cast(char[])password).ptr, password.length, salt.ptr, salt.length, n, r, p, maxMemory, hash.ptr, length) <= 0) {
  341. throw new CryptographicException("Unable to calculate SCrypt hash.");
  342. }
  343. return hash;
  344. }
  345. unittest
  346. {
  347. import std.digest;
  348. import std.stdio;
  349. writeln("Testing SCrypt Extended with Defaults:");
  350. ubyte[48] salt = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  351. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
  352. 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF ];
  353. ubyte[] vec2 = scrypt_ex("abc", salt, 1_048_576, 8, 1, 1_074_790_400, 64);
  354. ubyte[] vec3 = scrypt_ex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", salt, 1_048_576, 8, 1, 1_074_790_400, 64);
  355. writeln(toHexString!(LetterCase.lower)(vec2));
  356. writeln(toHexString!(LetterCase.lower)(vec3));
  357. assert(toHexString!(LetterCase.lower)(vec2) == "134fca5087e04c2a79e0ea2c793660f19d466db74a069e1f2e4da2b177d51402501bd39ffc592b9419ec0280cc17dca7af8df54f836179d69a4b9e9f6b9467fd");
  358. assert(toHexString!(LetterCase.lower)(vec3) == "45397ec370eb31f3155ad162d83ec165ff8e363bc4e03c1c61c5a31ad17d0dac51d9e8911f32e9b588adf284a9de24561483dbaf0ea519b6a29ecae77eab5b90");
  359. }