using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace APress.DotNetSecurity.Chapter2.SymmetricAlgorithmEvaluator
{
class SymmetricAlgorithmEvaluatorTester
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Creating a RijndaelManaged instance...");
SymmetricAlgorithm symAlg = new RijndaelManaged();
symAlg.GenerateIV();
Console.WriteLine("Generated IV value is " +
ArrayToHexString(symAlg.IV));
Console.WriteLine("Block size is " + symAlg.BlockSize.ToString());
Console.WriteLine("Key size is " + symAlg.KeySize.ToString());
Console.WriteLine("Key value is " +
ArrayToHexString(symAlg.Key));
foreach(KeySizes ks in symAlg.LegalKeySizes)
{
int currentSize = ks.MinSize;
do
{
Console.WriteLine("Legal key size: " + currentSize.ToString());
currentSize += ks.SkipSize;
} while(currentSize <= ks.MaxSize);
}
Console.WriteLine("Mode is " + symAlg.Mode.ToString());
Console.WriteLine("Padding type is " + symAlg.Padding.ToString());
Console.WriteLine("Input the desired key size:");
int desiredKeySize = Int32.Parse(Console.ReadLine());
KeySizesEx kse = new KeySizesEx(symAlg.LegalKeySizes);
if(true == kse.IsValidKeySize(desiredKeySize))
{
Console.WriteLine(desiredKeySize.ToString() +
" is a valid key size.");
}
else
{
Console.WriteLine(desiredKeySize.ToString() +
" is NOT a valid key size.");
}
}
catch(CryptographicUnexpectedOperationException cuoe)
{
Console.WriteLine("CryptographicUnexpectedOperationException: "
+ cuoe.Message);
Console.WriteLine(cuoe.StackTrace);
}
catch(CryptographicException ce)
{
Console.WriteLine("CryptographicException: " + ce.Message);
Console.WriteLine(ce.StackTrace);
}
catch(Exception ge)
{
Console.WriteLine("Exception: " + ge.GetType().Name + " " + ge.Message);
Console.WriteLine(ge.StackTrace);
}
finally
{
Console.WriteLine("Press the return key to continue...");
Console.Read();
}
}
private static String ArrayToHexString(byte[] ByteData)
{
StringBuilder retVal = new StringBuilder();
foreach(byte b in ByteData)
{
retVal.Append(b.ToString("X2"));
retVal.Append(" ");
}
retVal.Remove(retVal.Length - 1, 1);
return retVal.ToString();
}
}
public class KeySizesEx
{
private KeySizes[] ks = null;
public KeySizesEx(KeySizes[] ks)
{
this.ks = ks;
}
public bool IsValidKeySize(int DesiredSize)
{
bool retVal = false;
foreach(KeySizes keySize in ks)
{
if(DesiredSize >= keySize.MinSize &&
DesiredSize <= keySize.MaxSize &&
(DesiredSize % keySize.SkipSize) == 0)
{
retVal = true;
break;
}
}
return retVal;
}
}
}