Search code examples
azure-rm-templateazure-resource-manager

Azure ARM uniqueString function mimic


I need to deploy Sql Databases into an Azure Sql Server using to ways: the ARM template way, and a more custom way using C# code. There's a ARM template function called uniqueString(string) that generate a pseudo random hash of a given string. It's a deterministic pure function.

I need to find a way to exactly mimic the behaviour of this function from my C# code. ie I need to reproduce this function into my C# code.

Where can i find the algorithm used by the ARM Api ?

MSDN reference for uniqueString()


Solution

  • I found some PowerShell code to do this here: https://blogs.technet.microsoft.com/389thoughts/2017/12/23/get-uniquestring-generate-unique-id-for-azure-deployments/

    I converted this code to C#:

    public string GetUniqueString(string id, int length = 13)
    {
        string result = "";
        var buffer = System.Text.Encoding.UTF8.GetBytes(id);
        var hashArray = new System.Security.Cryptography.SHA512Managed().ComputeHash(buffer);
        for(int i = 1; i <= length; i++)
        {
            var b = hashArray[i];
            var c = Convert.ToChar((b % 26) + (byte)'a');
            result = result + c;
        }
    
        return result;
    }