Search code examples
encryptioncryptographyimplementationhmachmacsha1

What implementations allow me to detect failed HMAC validations to detect active attacks?


I'm trying to bring awareness around the need for authentication with encryption by using software to alert and report on failed MAC verification attempts, and sharing the results with middle management.

I'm not a cryptographer, but I see the value in a proper implementation. Ideally I'd like to create a report that says X attacks were prevented.

Is this a valid idea, or is it overly simplistic? If not, where should I start in implementing it? (Low level AES, PGP, etc?)


Solution

  • Here is a C# MAC code sample that could be modified to alert or log when authentication fails. This is an incomplete sample that shouldn't be used AS-IS since many other details need to be considered before implementing Authenticate-then-Encrypt (AtE) or Encrypt-then-Authenticate (EtA)

    It would be nice to know what performance counter, log file, or DLL exception relates to this error. I'll be investigating BouncyCastle to see where the corresponding exception is.

    // Compares the key in the source file with a new key created for the data portion of the file. If the keys 
    // compare the data has not been tampered with.
    public static bool VerifyFile(byte[] key, String sourceFile)
    {
        bool err = false;
        // Initialize the keyed hash object. 
        using (HMACSHA1 hmac = new HMACSHA1(key))
        {
            // Create an array to hold the keyed hash value read from the file.
            byte[] storedHash = new byte[hmac.HashSize / 8];
            // Create a FileStream for the source file.
            using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
            {
                // Read in the storedHash.
                inStream.Read(storedHash, 0, storedHash.Length);
                // Compute the hash of the remaining contents of the file.
                // The stream is properly positioned at the beginning of the content, 
                // immediately after the stored hash value.
                byte[] computedHash = hmac.ComputeHash(inStream);
                // compare the computed hash with the stored value
    
                for (int i = 0; i < storedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        err = true;
                    }
                }
            }
        }
        if (err)
        {
            Console.WriteLine("Hash values differ! Signed file has been tampered with!");
            // 
            // 
            // <-------- This is where the MAC alerting would go
            // 
            // 
    
            return false;
        }
        else
        {
            Console.WriteLine("Hash values agree -- no tampering occurred.");
            return true;
        }
    
    } //end VerifyFile