1 module chloride.auth; 2 3 import chloride.core; 4 import chloride.random : randomArray; 5 6 import deimos.sodium.crypto_auth; 7 8 /// 9 unittest { 10 import std..string : representation; 11 immutable ubyte[] message = representation("hello"); 12 auto key = makeAuthKey(); 13 auto mac = authenticateMessage(message, key); 14 assert(verifyMac(mac, message, key)); 15 } 16 17 alias AuthKey = ubyte[crypto_auth_KEYBYTES]; 18 alias Mac = ubyte[crypto_auth_BYTES]; 19 20 /** 21 * Generate a key for use with authentication. 22 */ 23 alias makeAuthKey = randomArray!AuthKey; 24 25 /** 26 * Create an authentication Mac for a message, signed with `key`. 27 */ 28 Mac authenticateMessage(in ubyte[] message, in AuthKey key) { 29 Mac mac = void; 30 auto result = crypto_auth(mac.ptr, message.ptr, message.length, key.ptr); 31 enforceSodium(result == 0); 32 return mac; 33 } 34 35 /** 36 * Verify message authentication with a secret key. 37 */ 38 bool verifyMac(in Mac mac, in ubyte[] message, in AuthKey key) { 39 return crypto_auth_verify(mac.ptr, message.ptr, message.length, key.ptr) == 0; 40 }