major source structure and module name changes

This commit is contained in:
soochoi
2006-06-07 16:34:19 +00:00
parent 5c75241b4b
commit 1fa6f07e83
651 changed files with 0 additions and 0 deletions

731
micasad/lss/CASACrypto.cs Normal file
View File

@@ -0,0 +1,731 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
#if LINUX
using Mono.Unix;
#endif
using sscs.common;
using sscs.constants;
namespace sscs.crypto
{
public class CASACrypto
{
private const int SALTSIZE = 64;
private const int ITERATION_COUNT = 1000;
private const int HASH_SIZE = 32;
internal static byte[] Generate16ByteKeyFromString(string sTheString, string sFilepath, bool bUseOldMethod)
{
byte[] baKey = new byte[16]; //return value
try
{
Rfc2898DeriveBytes pkcs5 = new Rfc2898DeriveBytes(sTheString, SALTSIZE, ITERATION_COUNT, bUseOldMethod);
baKey = pkcs5.GetBytes(16);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Key generation failed");
baKey = null;
}
return baKey;
}
internal static bool StoreKeySetUsingMasterPasscode(byte[] key,
byte[] IV, byte[] baMasterPasscode, string fileName)
{
bool bRet = false;
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor;
encryptor = myRijndael.CreateEncryptor(baMasterPasscode, GenerateAndSaveIV(fileName, myRijndael));
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(key);
fsEncrypt.Write(hash,0,hash.Length);
fsEncrypt.Flush();
csEncrypt = new CryptoStream(fsEncrypt, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(key, 0, key.Length);
csEncrypt.FlushFinalBlock();
bRet = true;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to store the generated key");
bRet = false;
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
return bRet;
}
internal static byte[] GetKeySetFromFile(byte[] baMasterPasscode,
string fileName )
{
byte[] baSavedKey = null;
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
try
{
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if(!File.Exists(fileName))
#endif
{
return null;
}
/* Get a decryptor that uses the same key and IV
* as the encryptor.
*/
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(baMasterPasscode, RetrieveIV(fileName, baMasterPasscode));
//Now decrypt
fsDecrypt = new FileStream(fileName, FileMode.Open);
byte[] storedHash = new byte[32];
fsDecrypt.Read(storedHash,0,storedHash.Length);
csDecrypt = new CryptoStream(fsDecrypt, decryptor, CryptoStreamMode.Read);
baSavedKey = new byte[32];
//Read the data out of the crypto stream.
csDecrypt.Read(baSavedKey, 0, baSavedKey.Length);
SHA256 sha = new SHA256Managed();
byte[] newHash = sha.ComputeHash(baSavedKey);
for( int i = 0 ; i < 32; i++ )
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to get the stored key");
baSavedKey = null;
}
if (csDecrypt != null)
csDecrypt.Close();
if ( fsDecrypt != null )
fsDecrypt.Close();
return baSavedKey;
}
internal static void EncryptDataAndWriteToFile(byte[] xmlData,
byte[] key, string fileName)
{
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] baIV = GenerateAndSaveIV(fileName, myRijndael);
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, baIV);
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(xmlData);
fsEncrypt.Write(hash,0,hash.Length);
fsEncrypt.Flush();
#if CLEAR
byte[] dup = (byte[])xmlData.Clone();
// write clear file
FileStream fsClear = new FileStream(fileName + ".xml", FileMode.Create);
fsClear.Write(dup, 0, dup.Length);
fsClear.Flush();
fsClear.Close();
#endif
csEncrypt = new CryptoStream(fsEncrypt, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(xmlData, 0, xmlData.Length);
csEncrypt.FlushFinalBlock();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Encrypting and storing to file failed.");
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
}
internal static byte[] ReadFileAndDecryptData(byte[] key,
string fileName)
{
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
try
{
byte[] IV = new byte[16];
for(int z = 0 ; z < 16; z++ )
IV[z] = key[z];
//Get a decryptor that uses the same key and IV as the encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] baIV = RetrieveIV(fileName, IV);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, baIV);
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if(!File.Exists(fileName))
#endif
{
return null;
}
//Now decrypt
fsDecrypt = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] storedHash = new byte[HASH_SIZE];
fsDecrypt.Read(storedHash,0,storedHash.Length);
csDecrypt = new CryptoStream(fsDecrypt, decryptor, CryptoStreamMode.Read);
if(fsDecrypt.Length < HASH_SIZE )
{
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
ulong fileLen = (ulong)(fsDecrypt.Length - HASH_SIZE);
byte[] fromEncrypt = new byte[fileLen];
//Read the data out of the crypto stream.
int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
byte[] tmpEncrypt = new byte[bytesRead];
for(int i = 0 ; i < bytesRead; i++ )
tmpEncrypt[i] = fromEncrypt[i];
SHA256 sha = new SHA256Managed();
byte[] newHash = sha.ComputeHash(tmpEncrypt);
for( int i = 0 ; i < 32; i++ )
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
}
try
{
csDecrypt.Close();
}
catch { }
try
{
fsDecrypt.Close();
}
catch { }
return tmpEncrypt;
}
catch(Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
if (csDecrypt != null)
{
try
{
csDecrypt.Close();
}
catch
{
}
}
if( fsDecrypt != null )
{
try
{
fsDecrypt.Close();
}
catch
{
}
}
return null;
}
/* The methods EncryptData() and DecryptData() would be
* required when we use a database to store secrets.
*/
/* Encrypts the data with the key and returns the encrypted buffer.
*/
/*
internal static byte[] EncryptData(byte[] data, byte[] key)
{
try
{
byte[] IV = new byte[16];
int i = 0;
for(i = 0 ; i < 16; i++ )
IV[i] = key[i];
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream ms1 = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(ms1, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
return ms1.ToArray();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
*/
/* Decrypts the buffer(encrypted) with the key and returns the
* decrypted data.
*/
/*
internal static byte[] DecryptData(byte[] buffer, byte[] key)
{
try
{
byte[] IV = new byte[16];
for(int i = 0 ; i < 16; i++ )
IV[i] = key[i];
//Get a decryptor that uses the same key and IV as the encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream ms1 = new MemoryStream(buffer);
CryptoStream csDecrypt = new CryptoStream(ms1, decryptor, CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[buffer.Length];
//Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return fromEncrypt;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
*/
/* This method checks if we can get the master passcode by
* decrypting the passwds file ( where we store all possible
* passwds cross-encrypted.
*
* TBD : As we are storing master passcode and the keys in 2
* different files, we need to take care of cases when 1 of the files
* is deleted.
*/
internal static bool CheckIfMasterPasscodeIsAvailable(string desktopPasswd, string fileName)
{
return (File.Exists(fileName));
}
internal static byte[] GetMasterPasscode(string desktopPasswd, string fileName)
{
byte[] mp = DecryptMasterPasscodeUsingString(desktopPasswd, fileName, false);
return mp;
}
/* TBD - There must be a way, where we establish the integrity of
* the files where we store the keys and master passcode.
* Use a marker ?
*/
// Used to save the MasterPasscode encrypted with Desktop login, etc
internal static void EncryptAndStoreMasterPasscodeUsingString(
byte[] baMasterPasscode,
string passwd,
string fileName)
{
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
if(File.Exists(fileName))
File.Delete(fileName);
byte[] baKey = Generate16ByteKeyFromString(passwd, null, false);
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor;
encryptor = myRijndael.CreateEncryptor(baKey, GenerateAndSaveIV(fileName, myRijndael));
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName,FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
csEncrypt = new CryptoStream(fsEncrypt, encryptor,
CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(baMasterPasscode, 0, baMasterPasscode.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Close();
fsEncrypt.Close();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
if (csEncrypt != null)
{
csEncrypt.Close();
}
if( fsEncrypt != null )
{
fsEncrypt.Close();
}
}
public static byte[] DecryptMasterPasscodeUsingString(string passwd,
string fileName, bool bTryOldMethod)
{
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
byte[] baSavedMasterPasscode = null;
try
{
byte[] baKey = Generate16ByteKeyFromString(passwd, fileName, bTryOldMethod);
/* Get a decryptor that uses the same key and
* IV as the encryptor.
*/
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(baKey, RetrieveIV(fileName, baKey));
//Now decrypt
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if (!File.Exists(fileName))
#endif
{
return null;
}
fsDecrypt = new FileStream(fileName, FileMode.Open);
csDecrypt = new CryptoStream(fsDecrypt, decryptor,
CryptoStreamMode.Read);
baSavedMasterPasscode = new byte[16];
//Read the data out of the crypto stream.
csDecrypt.Read(baSavedMasterPasscode, 0, 16);
}
catch (Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to decrypt master passode");
baSavedMasterPasscode = null;
}
try
{
if (csDecrypt != null)
csDecrypt.Close();
}
catch { }
if (fsDecrypt != null)
fsDecrypt.Close();
return baSavedMasterPasscode;
}
internal static byte[] GetMasterPasscodeUsingMasterPasswd(
string mPasswd,
string fileName,
bool bUseOldMethod)
{
byte[] baMasterPasscode;
try
{
if(File.Exists(fileName))
{
/* Decrypt the passcode from the file using master passwd.
* and return the decrypted passcode.
*/
baMasterPasscode = DecryptMasterPasscodeUsingString(mPasswd, fileName, bUseOldMethod);
return baMasterPasscode;
}
else
return null;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Failed to get master passcode from master password.");
}
return null;
}
internal static byte[] GetMasterPasscodeUsingDesktopPasswd(
string desktopPasswd,
string fileName,
bool bUseOldMethod)
{
byte[] passcode;
try
{
if(File.Exists(fileName))
{
/* Decrypt the passcode from the file using desktop passwd.
* and return the decrypted passcode.
*/
passcode = DecryptMasterPasscodeUsingString(desktopPasswd,
fileName, bUseOldMethod);
return passcode;
}
else
return null;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Failed to get master passcode using desktop passwd");
}
return null;
}
//internal static string GenerateMasterPasscodeUsingDesktopPasswd(
internal static byte[] GenerateMasterPasscodeUsingString(
string desktopPasswd,
string fileName,
string validationFile,
UserIdentifier userId
)
{
try
{
byte[] baPasscode;
// use AES to generate a random 16 byte key;
RijndaelManaged myRijndael = new RijndaelManaged();
myRijndael.KeySize = 128;
//Create a new key and initialization vector.
myRijndael.GenerateKey();
baPasscode = myRijndael.Key;
EncryptAndStoreMasterPasscodeUsingString(baPasscode,
desktopPasswd,
fileName);
EncryptDataAndWriteToFile(
Encoding.Default.GetBytes(
ConstStrings.MICASA_VALIDATION_STRING),
baPasscode,
validationFile);
return baPasscode;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Generation of master passcode failed.");
}
return null;
}
public static bool ValidatePasscode(byte[] baPasscode, string fileName)
{
/* Here we decrpyt a well known string, throw exception
* if not successful
* A well-known string is encrpyted by the Passcode and saved
*/
CSSSLogger.DbgLog("Validate called");
if ((baPasscode == null) || baPasscode.Length < 1 )
return false;
try
{
byte[] baString = ReadFileAndDecryptData(baPasscode, fileName);
string sString = Encoding.Default.GetString(baString);
char[] trimChars = {'\0'};
sString = sString.TrimEnd(trimChars);
if( ConstStrings.MICASA_VALIDATION_STRING.Equals(sString))
{
CSSSLogger.DbgLog("Passed");
return true;
}
else
{
CSSSLogger.DbgLog("Failed");
return false;
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Validation of passcode failed.");
}
return false;
}
private static byte[] GenerateAndSaveIV(string sFileName, RijndaelManaged theRiManaged)
{
theRiManaged.GenerateIV();
byte[] baIV = theRiManaged.IV;
try
{
if (File.Exists(sFileName + ".IV"))
File.Delete(sFileName + ".IV");
// now save this
FileStream fs = new FileStream(sFileName + ".IV", FileMode.Create);
fs.Write(baIV, 0, 16);
fs.Flush();
fs.Close();
File.SetAttributes(sFileName + ".IV", FileAttributes.Hidden);
}
catch (Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
return baIV;
}
private static byte[] RetrieveIV(string sFileName, byte[] baOrigValue)
{
byte[] IV = new byte[16];
// check for file existence
try
{
FileStream fs = new FileStream(sFileName + ".IV", FileMode.Open);
fs.Read(IV, 0, 16);
fs.Close();
return IV;
}
catch (Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
// original IV size was 16 bytes, copy that much
if (baOrigValue.Length == 16)
{
return (byte[])baOrigValue.Clone();
}
else
{
for (int i=0; i<16; i++)
{
IV[i] = baOrigValue[i];
}
return IV;
}
}
private static void DumpIV(byte[] iv)
{
for (int i=0; i<iv.Length; i++)
{
Console.Write(iv[i] + " ");
}
Console.WriteLine("\r\n");
}
}
}

328
micasad/lss/FastRandom.cs Normal file
View File

@@ -0,0 +1,328 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
namespace sscs.lss
{
/*
* Yes, if you want to go ahead and attach an LGPL header to the source
* file then that's fine. I hereby grant Novell Inc. permission to use the
* FastRandom.cs random number generator source code under the Lesser GNU
* Public Licesne (LGPL).
*
* Apr 19, 2006: received by jnorman@novell.com from Colin Green
*
* License also signed and sent to Novell on May 2, 2006.
*/
/// <summary>
/// A fast random number generator for .NET
/// Colin Green, January 2005
///
/// September 4th 2005
/// Added NextBytesUnsafe() - commented out by default.
/// Fixed bug in Reinitialise() - y,z and w variables were not being reset.
///
/// Key points:
/// 1) Based on a simple and fast xor-shift pseudo random number generator (RNG) specified in:
/// Marsaglia, George. (2003). Xorshift RNGs.
/// http://www.jstatsoft.org/v08/i14/xorshift.pdf
///
/// This particular implementation of xorshift has a period of 2^128-1. See the above paper to see
/// how this can be easily extened if you need a longer period. At the time of writing I could find no
/// information on the period of System.Random for comparison.
///
/// 2) Faster than System.Random. Up to 15x faster, depending on which methods are called.
///
/// 3) Direct replacement for System.Random. This class implements all of the methods that System.Random
/// does plus some additional methods. The like named methods are functionally equivalent.
///
/// 4) Allows fast re-initialisation with a seed, unlike System.Random which accepts a seed at construction
/// time which then executes a relatively expensive initialisation routine. This provides a vast speed improvement
/// if you need to reset the pseudo-random number sequence many times, e.g. if you want to re-generate the same
/// sequence many times. An alternative might be to cache random numbers in an array, but that approach is limited
/// by memory capacity and the fact that you may also want a large number of different sequences cached. Each sequence
/// can each be represented by a single seed value (int) when using FastRandom.
///
/// Notes.
/// A further performance improvement can be obtained by declaring local variables as static, thus avoiding
/// re-allocation of variables on each call. However care should be taken if multiple instances of
/// FastRandom are in use or if being used in a multi-threaded environment.
///
/// </summary>
public class FastRandom
{
// The +1 ensures NextDouble doesn't generate 1.0
const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0);
const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0);
const uint Y = 842502087, Z = 3579807591, W = 273326509;
uint x, y, z, w;
#region Constructors
/// <summary>
/// Initialises a new instance using time dependent seed.
/// </summary>
public FastRandom()
{
// Initialise using the system tick count.
Reinitialise((int)Environment.TickCount);
}
/// <summary>
/// Initialises a new instance using an int value as seed.
/// This constructor signature is provided to maintain compatibility with
/// System.Random
/// </summary>
public FastRandom(int seed)
{
Reinitialise(seed);
}
#endregion
#region Public Methods [Reinitialisation]
/// <summary>
/// Reinitialises using an int value as a seed.
/// </summary>
/// <param name="seed"></param>
public void Reinitialise(int seed)
{
// The only stipulation stated for the xorshift RNG is that at least one of
// the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing
// resetting of the x seed
x = (uint)seed;
y = Y;
z = Z;
w = W;
}
#endregion
#region Public Methods [Next* methods]
/// <summary>
/// Generates a uint. Values returned are over the full range of a uint,
/// uint.MinValue to uint.MaxValue, including the min and max values.
/// </summary>
/// <returns></returns>
public uint NextUInt()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
}
/// <summary>
/// Generates a random int. Values returned are over the range 0 to int.MaxValue-1.
/// MaxValue is not generated to remain functionally equivalent to System.Random.Next().
/// If you require an int from the full range, including negative values then call
/// NextUint() and cast the value to an int.
/// </summary>
/// <returns></returns>
public int Next()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
return (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))));
}
/// <summary>
/// Generates a random int over the range 0 to upperBound-1, and not including upperBound.
/// </summary>
/// <param name="upperBound"></param>
/// <returns></returns>
public int Next(int upperBound)
{
if (upperBound < 0)
throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0");
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// The explicit int cast before the first multiplication gives better performance.
// See comments in NextDouble.
return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * upperBound);
}
/// <summary>
/// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound.
/// upperBound must be >= lowerBound. lowerBound may be negative.
/// </summary>
/// <param name="lowerBound"></param>
/// <param name="upperBound"></param>
/// <returns></returns>
public int Next(int lowerBound, int upperBound)
{
if (lowerBound > upperBound)
throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound");
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// The explicit int cast before the first multiplication gives better performance.
// See comments in NextDouble.
int range = upperBound - lowerBound;
if (range < 0)
{ // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower).
// We also must use all 32 bits of precision, instead of the normal 31, which again is slower.
return lowerBound + (int)((REAL_UNIT_UINT * (double)(w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound));
}
// 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int anf gain
// a little more performance.
return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * (double)range);
}
/// <summary>
/// Generates a random double. Values returned are from 0.0 up to but not including 1.0.
/// </summary>
/// <returns></returns>
public double NextDouble()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// Here we can gain a 2x speed improvement by generating a value that can be cast to
// an int instead of the more easily available uint. If we then explicitly cast to an
// int the compiler will then cast the int to a double to perform the multiplication,
// this final cast is a lot faster than casting from a uint to a double. The extra cast
// to an int is very fast (the allocated bits remain the same) and so the overall effect
// of the extra cast is a significant performance improvement.
return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))));
}
/// <summary>
/// Fills the provided byte array with random bytes.
/// Increased performance is achieved by dividing and packaging bits directly from the
/// random number generator and storing them in 4 byte 'chunks'.
/// </summary>
/// <param name="buffer"></param>
public void NextBytes(byte[] buffer)
{
// Fill up the bulk of the buffer in chunks of 4 bytes at a time.
uint x = this.x, y = this.y, z = this.z, w = this.w;
int i = 0;
uint t;
for (; i < buffer.Length - 3; )
{
// Generate 4 bytes.
t = (x ^ (x << 11));
x = y; y = z; z = w;
w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
buffer[i++] = (byte)(w & 0x000000FF);
buffer[i++] = (byte)((w & 0x0000FF00) >> 8);
buffer[i++] = (byte)((w & 0x00FF0000) >> 16);
buffer[i++] = (byte)((w & 0xFF000000) >> 24);
}
// Fill up any remaining bytes in the buffer.
if (i < buffer.Length)
{
// Generate 4 bytes.
t = (x ^ (x << 11));
x = y; y = z; z = w;
w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
buffer[i++] = (byte)(w & 0x000000FF);
if (i < buffer.Length)
{
buffer[i++] = (byte)((w & 0x0000FF00) >> 8);
if (i < buffer.Length)
{
buffer[i++] = (byte)((w & 0x00FF0000) >> 16);
if (i < buffer.Length)
{
buffer[i] = (byte)((w & 0xFF000000) >> 24);
}
}
}
}
this.x = x; this.y = y; this.z = z; this.w = w;
}
// /// <summary>
// /// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation
// /// thus providing a nice speedup. Note that this requires the unsafe compilation flag to be specified
// /// and so is commented out by default.
// /// </summary>
// /// <param name="buffer"></param>
// public unsafe void NextBytesUnsafe(byte[] buffer)
// {
// if(buffer.Length % 4 != 0)
// throw new ArgumentException("Buffer length must be divisible by 4", "buffer");
//
// uint x=this.x, y=this.y, z=this.z, w=this.w;
// uint t;
//
// fixed(byte* pByte0 = buffer)
// {
// uint* pDWord = (uint*)pByte0;
// for(int i = 0, len = buffer.Length>>2; i < len; i++)
// {
// t=(x^(x<<11));
// x=y; y=z; z=w;
// *pDWord++ = w = (w^(w>>19))^(t^(t>>8));
// }
// }
//
// this.x=x; this.y=y; this.z=z; this.w=w;
// }
// Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned
// with bitBufferIdx.
uint bitBuffer;
int bitBufferIdx = 32;
/// <summary>
/// Generates random bool.
/// Increased performance is achieved by buffering 32 random bits for
/// future calls. Thus the random number generator is only invoked once
/// in every 32 calls.
/// </summary>
/// <returns></returns>
public bool NextBool()
{
if (bitBufferIdx == 32)
{
// Generate 32 more bits.
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
bitBuffer = w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
// Reset the idx that tells us which bit to read next.
bitBufferIdx = 1;
return (bitBuffer & 0x1) == 1;
}
bitBufferIdx++;
return ((bitBuffer >>= 1) & 0x1) == 1;
}
#endregion
}
}

520
micasad/lss/LocalStorage.cs Normal file
View File

@@ -0,0 +1,520 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Security.Cryptography;
using System.Xml;
#if LINUX
using Mono.Unix.Native;
#endif
using sscs.cache;
using sscs.crypto;
using sscs.common;
using sscs.constants;
using Novell.CASA.MiCasa.Common;
namespace sscs.lss
{
/// <summary>
/*
* This class is a service to store data persistently.
* How it does this is determined by implementation within the
* private methods (File system using file(s), database, etc)
* The MasterPasscode can be used to generate the key for
* encyption and decryption.
* If encrpytion is used, the private methods will also manage
* how the encyption key is to be stored and retrieved.
* Each piece of data is located by a DataID.
* This might be an individual credentail or
* a complete store.
*/
/* We might not need this as a separate class.
* Depending on the db changes, we can change this later.
*/
/// </summary>
public class LocalStorage
{
private byte[] m_baGeneratedKey = null;
private SecretStore userStore = null;
private int persistThreadSleepTime = 1000 * 60 * 5; //1000 * 30;
private Thread persistThread = null;
#if LINUX
Mono.Unix.UnixFileSystemInfo sockFileInfo;
Mono.Unix.UnixUserInfo sockFileOwner;
#endif
private static string LINUXID = "Unix";
internal LocalStorage(SecretStore store,byte[] baMasterPasscode)
{
userStore = store;
m_baGeneratedKey = baMasterPasscode;
LoadPersistentStore();
userStore.DumpSecretstore();
}
~LocalStorage()
{
if(persistThread != null)
{
persistThread.Abort();
persistThread.Join();
}
}
// allowing a user to choose the storage location is not approved yet
private LocalStorage(SecretStore store,
byte[] baMasterPasscode, string sStorageDirectory)
{
userStore = store;
m_baGeneratedKey = baMasterPasscode;
LoadPersistentStore();
userStore.DumpSecretstore();
}
private void StorePersistentData(string sDataID, byte[] baData)
{
}
private byte[] RetrievePersistentData(string sDataID)
{
return null;
}
public void PersistStoreWithDelay()
{
if (persistThread == null)
{
persistThread = new Thread(new ThreadStart(PersistStoreDelayThreadFn));
persistThread.Start();
}
}
public bool StopPersistence()
{
if(persistThread != null)
{
persistThread.Abort();
persistThread.Join();
}
return true;
}
public bool IsOwnedByRoot(string fileName)
{
#if LINUX
sockFileInfo = new Mono.Unix.UnixFileInfo(fileName);
sockFileOwner = sockFileInfo.OwnerUser;
if(0==sockFileOwner.UserId)
return true;
else
return false;
#else
return true;
#endif
}
private string GetDecryptedXml()
{
try
{
string fileName = userStore.GetPersistenceFilePath();
string tempFile = fileName;
int count = 0;
if(!File.Exists(fileName))
{
while(true)
{
// check for tmp file
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
{
File.Move(tempFile+".tmp", fileName);
break;
}
else
{
count++;
tempFile = fileName + count.ToString();
}
}
else
return null;
}
// delete tmp file if there
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
File.Delete(tempFile+".tmp");
}
}
byte[] baPasscode = null;
if (null != m_baGeneratedKey)
baPasscode = m_baGeneratedKey;
else
baPasscode = CASACrypto.GetMasterPasscode(userStore.GetDesktopPasswd(),userStore.GetPasscodeByDesktopFilePath());
if( null == baPasscode )
return null;
byte[] key = CASACrypto.GetKeySetFromFile(baPasscode,userStore.GetKeyFilePath());
if( null == key )
return null;
byte[] decryptedBuffer = CASACrypto.ReadFileAndDecryptData(key,fileName);
if( null == decryptedBuffer )
return null;
string temp = Encoding.UTF8.GetString(decryptedBuffer, 0, decryptedBuffer.Length);
return temp;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to get persistent store");
}
return null;
}
/* This method, uses the key to decrypt the persistent store
* and populates userStore with the persistent data.
*/
private bool LoadPersistentStore()
{
try
{
string xpath = "";
XmlDocument doc = new XmlDocument();
string xmlToLoad = GetDecryptedXml();
if(xmlToLoad != null)
{
doc.LoadXml(xmlToLoad);
#if false
XmlTextWriter writer = new XmlTextWriter("/home/poorna/.miCASA.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
#endif
}
else
{
return false;
}
xpath = "//" + XmlConsts.miCASANode;
XmlNode miCASANode = doc.SelectSingleNode(xpath);
if(miCASANode != null)
{
xpath = "descendant::" + XmlConsts.keyChainNode;
XmlNodeList keyChainNodeList = miCASANode.SelectNodes(xpath);
foreach(XmlNode node in keyChainNodeList)
{
XmlAttributeCollection attrColl = node.Attributes;
string keyChainId = (attrColl[XmlConsts.idAttr]).Value + "\0";
KeyChain keyChain = null;
if( userStore.CheckIfKeyChainExists(keyChainId) == false )
{
keyChain = new KeyChain(keyChainId);
userStore.AddKeyChain(keyChain);
}
else
{
keyChain = userStore.GetKeyChain(keyChainId);
}
xpath = "descendant::" + XmlConsts.secretNode;
XmlNodeList secretNodeList = node.SelectNodes(xpath);
foreach(XmlNode secretNode in secretNodeList)
{
attrColl = secretNode.Attributes;
string secretId = (attrColl[XmlConsts.idAttr]).Value + "\0";
xpath = "descendant::" + XmlConsts.valueNode;
Secret secret = new Secret(secretId);
if( keyChain.CheckIfSecretExists(secretId) == false)
{
keyChain.AddSecret(secret);
XmlNode secretValNode = (secretNode.SelectSingleNode(xpath));
xpath = "descendant::" + XmlConsts.keyNode;
XmlNodeList keyNodeList = secretValNode.SelectNodes(xpath);
secret = keyChain.GetSecret(secretId);
foreach(XmlNode keyNode in keyNodeList)
{
attrColl = keyNode.Attributes;
string key;
try
{
key = (attrColl[XmlConsts.idAttr]).Value;
}
catch (Exception)
{
// LinkedKey node, continue
continue;
}
xpath = "descendant::" + XmlConsts.keyValueNode;
XmlNode keyValNode = keyNode.SelectSingleNode(xpath);
string keyValue = keyValNode.InnerText;
secret.SetKeyValue(key,keyValue);
// add linked keys
xpath = "descendant::" + XmlConsts.linkedKeyNode;
XmlNodeList linkNodeList = keyNode.SelectNodes(xpath);
foreach(XmlNode linkNode in linkNodeList)
{
// get TargetSecretID
xpath = "descendant::" + XmlConsts.linkedTargetSecretNode;
XmlNode targetSecretNode = linkNode.SelectSingleNode(xpath);
string sSecretID = targetSecretNode.InnerText + "\0";
// get TargetSecretKey
xpath = "descendant::" + XmlConsts.linkedTargetKeyNode;
XmlNode targetKeyNode = linkNode.SelectSingleNode(xpath);
string sKeyID = targetKeyNode.InnerText;
LinkedKeyInfo lki = new LinkedKeyInfo(sSecretID, sKeyID, true);
KeyValue kv = secret.GetKeyValue(key);
kv.AddLink(lki);
}
}
}//if ends
}
}//end of traversing keyChainNodeList
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
// collect now to remove old data from memory
GC.Collect();
return true;
}
private void PersistStoreDelayThreadFn()
{
Thread.Sleep(15000);
PersistStore();
persistThread = null;
}
private void PersistStoreThreadFn()
{
while(true)
{
Thread.Sleep(persistThreadSleepTime);
PersistStore();
}
}
/* Persists the store to an xml file.
* TBD : Would we require any form of encoding?
*/
internal void PersistStore()
{
// userStore.DumpSecretstore();
try
{
MemoryStream ms1 = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms1,null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement(XmlConsts.miCASANode);
writer.WriteAttributeString(XmlConsts.versionAttr,"1.5");
{
IDictionaryEnumerator iter = (IDictionaryEnumerator)userStore.GetKeyChainEnumerator();
char [] tmpId;
string sTmpId;
while( iter.MoveNext() )
{
KeyChain kc = (KeyChain)iter.Value;
writer.WriteStartElement(XmlConsts.keyChainNode);
string kcId = kc.GetKey();
tmpId = new char[kcId.Length-1];
for(int i = 0; i < kcId.Length-1; i++ )
tmpId[i] = kcId[i];
sTmpId = new string(tmpId);
writer.WriteAttributeString(XmlConsts.idAttr,sTmpId);
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,kc.CreatedTime.ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,kc.ModifiedTime.ToString());
writer.WriteEndElement();
*/
IDictionaryEnumerator secIter = (IDictionaryEnumerator)(kc.GetAllSecrets());
while(secIter.MoveNext())
{
Secret secret = (Secret)secIter.Value;
writer.WriteStartElement(XmlConsts.secretNode);
string secretId = secret.GetKey();
tmpId = new char[secretId.Length-1];
for(int i = 0; i < secretId.Length-1; i++ )
tmpId[i] = secretId[i];
sTmpId = new string(tmpId);
writer.WriteAttributeString(XmlConsts.idAttr,sTmpId);
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,secret.CreatedTime.ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,secret.ModifiedTime.ToString());
writer.WriteEndElement();
*/
writer.WriteStartElement(XmlConsts.valueNode);
// byte[] byteArr = secret.GetValue();
IDictionaryEnumerator etor = (IDictionaryEnumerator)secret.GetKeyValueEnumerator();
while(etor.MoveNext())
{
string sKey = (string)etor.Key;
string value = secret.GetKeyValue(sKey).GetValue();
writer.WriteStartElement(XmlConsts.keyNode);
writer.WriteAttributeString(XmlConsts.idAttr, sKey);
writer.WriteStartElement(XmlConsts.keyValueNode);
writer.WriteString(value);
writer.WriteEndElement();
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,(secret.GetKeyValueCreatedTime(sKey)).ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,(secret.GetKeyValueModifiedTime(sKey)).ToString());
writer.WriteEndElement();
*/
// write all LinkKeys
Hashtable htLinkedKeys = secret.GetLinkedKeys(sKey);
if (htLinkedKeys != null)
{
IDictionaryEnumerator etorLinked = (IDictionaryEnumerator)htLinkedKeys.GetEnumerator();
while(etorLinked.MoveNext())
{
LinkedKeyInfo lki = (LinkedKeyInfo)etorLinked.Value;
writer.WriteStartElement(XmlConsts.linkedKeyNode);
writer.WriteStartElement(XmlConsts.linkedTargetSecretNode);
writer.WriteString(lki.GetLinkedSecretID().Substring(0, lki.GetLinkedSecretID().Length-1));
writer.WriteEndElement();
writer.WriteStartElement(XmlConsts.linkedTargetKeyNode);
writer.WriteString(lki.GetLinkedKeyID());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
/*
char[] chArr = new char[byteArr.Length];
for(int z = 0; z < byteArr.Length; z++)
chArr[z] = (char)byteArr[z];
string stringToStore = new string(chArr);
writer.WriteString(stringToStore);
*/
writer.WriteEndElement(); //end of value node
writer.WriteEndElement();
}
writer.WriteEndElement(); //keychain
}
}
writer.WriteEndElement(); //miCASA node
writer.WriteEndDocument();
writer.Flush();
writer.Close();
//byte[] key = CASACrypto.GetKeySetFromFile(CASACrypto.GetMasterPasscode(userStore.GetDesktopPasswd(),userStore.GetPasscodeByDesktopFilePath()),userStore.GetKeyFilePath());
byte[] key = CASACrypto.GetKeySetFromFile(m_baGeneratedKey, userStore.GetKeyFilePath());
string fileName = userStore.GetPersistenceFilePath();
string tempFile = fileName;
int count=0;
// rename existing file
if(File.Exists(fileName))
{
while(true)
{
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
{
File.Delete(tempFile+".tmp");
break;
}
else
{
count++;
tempFile = fileName + count.ToString();
}
}
else
break;
}
File.Move(fileName, tempFile+".tmp");
}
CASACrypto.EncryptDataAndWriteToFile(ms1.ToArray(),key,fileName);
//remove temp
if(File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
File.Delete(tempFile+".tmp");
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
}
}
}

View File

@@ -0,0 +1,270 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
//
// Rfc2898DeriveBytes.cs: RFC2898 (PKCS#5 v2) Key derivation for Password Based Encryption
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//using System.Runtime.InteropServices;
using System;
using System.Text;
using System.Security.Cryptography;
using sscs.lss;
namespace sscs.crypto {
//[ComVisible (true)]
public class Rfc2898DeriveBytes : DeriveBytes {
private const int defaultIterations = 1000;
private int _iteration;
private byte[] _salt;
private HMACSHA1 _hmac;
private byte[] _buffer;
private int _pos;
private int _f;
// constructors
public Rfc2898DeriveBytes (string password, byte[] salt)
: this (password, salt, defaultIterations)
{
}
public Rfc2898DeriveBytes (string password, byte[] salt, int iterations)
{
if (password == null)
throw new ArgumentNullException ("password");
Salt = salt;
IterationCount = iterations;
_hmac = new HMACSHA1 (Encoding.UTF8.GetBytes (password));
}
public Rfc2898DeriveBytes (byte[] password, byte[] salt, int iterations)
{
if (password == null)
throw new ArgumentNullException ("password");
Salt = salt;
IterationCount = iterations;
_hmac = new HMACSHA1 (password);
}
public Rfc2898DeriveBytes (string password, int saltSize)
: this (password, saltSize, defaultIterations)
{
}
public Rfc2898DeriveBytes(string password, int saltSize, int iterations)
: this (password, saltSize, iterations, false)
{
}
public Rfc2898DeriveBytes (string password, int saltSize, int iterations, bool bUseOldMethod)
{
if (password == null)
throw new ArgumentNullException ("password");
if (saltSize < 0)
throw new ArgumentOutOfRangeException ("invalid salt length");
if (bUseOldMethod)
{
Salt = GenerateOldSalt(password, saltSize);
}
else
{
Salt = GenerateNewSalt(password, saltSize);
}
IterationCount = iterations;
_hmac = new HMACSHA1 (Encoding.UTF8.GetBytes (password));
}
private static byte[] GenerateOldSalt(string password, int saltSize)
{
byte[] buffer = new byte[saltSize];
Random rand = new Random(password.GetHashCode());
rand.NextBytes(buffer);
return buffer;
}
private static byte[] GenerateNewSalt(string password, int saltSize)
{
int j = 0;
byte[] buffer = new byte[saltSize];
// iterate thru each character, creating a new Random,
// getting 2 bytes from each, until our salt buffer is full.
for (int i = 0; i < password.Length;)
{
char letter = password[i];
int iLetter = (int)letter;
FastRandom ranNum = new FastRandom(iLetter * (j+1));
byte[] temp = new byte[2];
ranNum.NextBytes(temp);
for (int k = 0; k < temp.Length; k++)
{
buffer[j++] = temp[k];
// get out if buffer is full
if (j >= saltSize)
{
return buffer;
}
}
i++;
// reset i if at end of password
if ((i + 1) > password.Length)
{
i = 0;
}
}
return buffer;
}
// properties
public int IterationCount
{
get { return _iteration; }
set {
if (value < 1)
throw new ArgumentOutOfRangeException ("IterationCount < 1");
_iteration = value;
}
}
public byte[] Salt {
get { return (byte[]) _salt.Clone (); }
set {
if (value == null)
throw new ArgumentNullException ("Salt");
if (value.Length < 8)
throw new ArgumentException ("Salt < 8 bytes");
_salt = (byte[])value.Clone ();
}
}
// methods
private byte[] F (byte[] s, int c, int i)
{
byte[] data = new byte [s.Length + 4];
Buffer.BlockCopy (s, 0, data, 0, s.Length);
byte[] int4 = BitConverter.GetBytes (i);
Array.Reverse (int4, 0, 4);
Buffer.BlockCopy (int4, 0, data, s.Length, 4);
// this is like j=0
byte[] u1 = _hmac.ComputeHash (data);
data = u1;
// so we start at j=1
for (int j=1; j < c; j++) {
byte[] un = _hmac.ComputeHash (data);
// xor
for (int k=0; k < 20; k++)
u1 [k] = (byte)(u1 [k] ^ un [k]);
data = un;
}
return u1;
}
public override byte[] GetBytes (int cb)
{
if (cb < 1)
throw new ArgumentOutOfRangeException ("cb");
int l = cb / 20; // HMACSHA1 == 160 bits == 20 bytes
int r = cb % 20; // remainder
if (r != 0)
l++; // rounding up
byte[] result = new byte [cb];
int rpos = 0;
if (_pos > 0) {
int count = Math.Min (20 - _pos, cb);
Buffer.BlockCopy (_buffer, _pos, result, 0, count);
if (count >= cb)
return result;
_pos = 0;
rpos = 20 - cb;
r = cb - rpos;
}
for (int i=1; i <= l; i++) {
_buffer = F (_salt, _iteration, ++_f);
int count = ((i == l) ? r : 20);
Buffer.BlockCopy (_buffer, _pos, result, rpos, count);
rpos += _pos + count;
_pos = ((count == 20) ? 0 : count);
}
return result;
}
public override void Reset ()
{
_buffer = null;
_pos = 0;
_f = 0;
}
}
}