Azure / api-management-policy-snippets

Re-usable examples of Azure API Management policies
MIT License
345 stars 157 forks source link

Encryption Policy not working #102

Closed falrnacn closed 1 year ago

falrnacn commented 1 year ago

Hi I tried running the policy statements in https://github.com/Azure/api-management-policy-snippets/blob/master/examples/Encrypt%20data%20using%20expressions.policy.xml but i get the foll exception

ExpressionValueEvaluationException: Expression evaluation failed. The specified initialization vector (IV) does not match the block size for this algorithm. Parameter name: iv at System.Security.Cryptography.AesCryptoServiceProvider.CreateEncryptor(Byte[] key, Byte[] iv) at Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.Context.CryptographyExtensions.Encrypt(Byte[] input, SymmetricAlgorithm alg, Byte[] key, Byte[] iv) at Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.Context.CryptographyExtensions.Encrypt(Byte[] input, String alg, Byte[] key, Byte[] iv)

I am using foll code snippet to generate the key and IV

` using System; using System.Security.Cryptography; public static class AESKeyandIVGenerator { public static string GenerateKey() { // Generate a 256-bit (32-byte) key byte[] key = new byte[32]; using var rng = System.Security.Cryptography.RandomNumberGenerator.Create(); rng.GetBytes(key); Convert.ToBase64String(key);
return BitConverter.ToString(key).Replace("-", ""); }

public static string GenerateIV()
{    
    byte[] iv = new byte[16];
    using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
    rng.GetBytes(iv);
    Convert.ToBase64String(iv); 
    return BitConverter.ToString(iv).Replace("-", "");
}

static void Main(string[] args)
{
    Console.WriteLine($"Hello! Your 256-bit (32-byte) key is: ");
    Console.WriteLine(GenerateKey());
    Console.WriteLine($"Hello! Your 168-bit (16-byte) IV is: ");
    Console.WriteLine(GenerateIV());        
}

} `

Sample output

Hello! Your 256-bit (32-byte) key is: B397B38678D727EF20F65915EC289A34CAAB9107EDB69DC4B26A61FB0B750463 Hello! Your 168-bit (16-byte) IV is: 5A78E054F381A06BA5049914C2604E9A

Can you let me know where i am going wrong?

falrnacn commented 1 year ago

@miaojiang Can you please check?

falrnacn commented 1 year ago

Resolved. It needed a 192 bit key.