Created
April 3, 2012 15:01
-
-
Save kamranayub/2292726 to your computer and use it in GitHub Desktop.
Validating key size for a SymmetricAlgorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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