Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created April 3, 2012 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/2292726 to your computer and use it in GitHub Desktop.
Save kamranayub/2292726 to your computer and use it in GitHub Desktop.
Validating key size for a SymmetricAlgorithm
// in a method
// alorithm = SymmetricAlgorithm
// keySize = int (in bits)
if (algorithm.ValidKeySize(keySize))
{
algorithm.KeySize = keySize;
}
else
{
throw new ArgumentException(
String.Format("{0} bits is not a valid key size for {1}. Valid key sizes: {2}",
keySize, algorithm.GetType().Name, GetFormattedKeySizes(algorithm)), "keySize");
}
// in the SymmetricEncryption class
/// <summary>
/// Returns a comma-separated list of key sizes for a given algorithm
/// </summary>
/// <param name="algorithm">Algorithm to use</param>
/// <returns></returns>
private static string GetFormattedKeySizes(SymmetricAlgorithm algorithm)
{
var keySizes = new List<int>();
foreach(var keySize in algorithm.LegalKeySizes)
{
// Max, min, skip
for (var i = keySize.MinSize; i <= keySize.MaxSize; i += keySize.SkipSize)
{
keySizes.Add(i);
}
}
return String.Join(", ", keySizes.Distinct().OrderBy(i => i).Select(i => i + " bits"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment