using System;
using System.Security.Cryptography;
using System.Text;
namespace Demo
{
internal class PKCSKeyGenerator
{
byte[] key = new byte[8], iv = new byte[8];
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
public byte[] Key { get { return key; } }
public byte[] IV { get { return iv; } }
public ICryptoTransform Encryptor { get { return des.CreateEncryptor(key, iv); } }
public ICryptoTransform Decryptor { get { return des.CreateDecryptor(key, iv); } }
public PKCSKeyGenerator() { }
public PKCSKeyGenerator(String keystring, byte[] salt, int md5iterations, int segments)
{
Generate(keystring, salt, md5iterations, segments);
}
public ICryptoTransform Generate(String keystring, byte[] salt, int md5iterations, int segments)
{
int HASHLENGTH = 16;
byte[] keymaterial = new byte[HASHLENGTH * segments];
byte[] psbytes;
psbytes = Encoding.UTF8.GetBytes(keystring);
byte[] data00 = new byte[psbytes.Length + salt.Length];
Array.Copy(psbytes, data00, psbytes.Length);
Array.Copy(salt, 0, data00, psbytes.Length, salt.Length);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = null;
byte[] hashtarget = new byte[HASHLENGTH + data00.Length];
for (int j = 0; j < segments; j++)
{
if (j == 0)
{
result = data00;
}
else
{
Array.Copy(result, hashtarget, result.Length);
Array.Copy(data00, 0, hashtarget, result.Length, data00.Length);
result = hashtarget;
}
for (int i = 0; i < md5iterations; i++)
{
result = md5.ComputeHash(result);
}
Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length);
}
Array.Copy(keymaterial, 0, key, 0, 8);
Array.Copy(keymaterial, 8, iv, 0, 8);
return Encryptor;
}
}
}