Я начал создавать безопасный тип строки - который я называю SecureStringV2 - чтобы расширить существующий тип SecureString в .Net framework. Этот новый тип добавит некоторые базовые функциональные возможности (проверка на равенство, сравнение и т. Д.) К существующему типу, но при этом сохранит безопасность, обеспечиваемую типом SecureString, который очищает все из памяти после использования типов. Я планирую реализовать эти функции, используя класс Marshal и алгоритмы хеширования. Указатели о том, как это сделать и сделать правильно, будут оценены. Кто-нибудь из вас видит проблемы с моими идеями по реализации этого? Спасибо:)
Обновление: это то, куда мои идеи привели меня до сих пор в отношении основного класса библиотеки. взгляни и дай мне знать твои мысли.
/// <summary>
/// This class is extension of the SecureString Class in the .Net framework.
/// It provides checks for equality of multiple SStringV2 instances and maintains
/// the security provided by the SecureString Class
/// </summary>
public class SStringV2 : IEquatable<SStringV2> , IDisposable
{
private SecureString secureString = new SecureString();
private Byte[] sStringBytes;
private String hash = string.Empty;
/// <summary>
/// SStringV2 constructor
/// </summary>
/// <param name="confidentialData"></param>
public SStringV2(ref Char[] confidentialData)
{
GCHandle charArrayHandle = GCHandle.Alloc(confidentialData, GCHandleType.Pinned);
// The unmanaged string splices a zero byte inbetween every two bytes
//and at its end doubling the total number of bytes
sStringBytes = new Byte[confidentialData.Length*2];
try
{
for (int index = 0; index < confidentialData.Length; ++index)
{
secureString.AppendChar(confidentialData[index]);
}
}
finally
{
ZeroOutSequence.ZeroOutArray(ref confidentialData);
charArrayHandle.Free();
}
}
/// <summary>
/// Computes the hash value of the secured string
/// </summary>
private void GenerateHash()
{
IntPtr unmanagedRef = Marshal.SecureStringToBSTR(secureString);
GCHandle byteArrayHandle = GCHandle.Alloc(sStringBytes, GCHandleType.Pinned);
Marshal.Copy(unmanagedRef, sStringBytes, 0, sStringBytes.Length);
SHA256Managed SHA256 = new SHA256Managed();
try
{
hash = Convert.ToBase64String(SHA256.ComputeHash(this.sStringBytes));
}
finally
{
SHA256.Clear();
ZeroOutSequence.ZeroOutArray(ref sStringBytes);
byteArrayHandle.Free();
Marshal.ZeroFreeBSTR(unmanagedRef);
}
}
#region IEquatable<SStringV2> Members
public bool Equals(SStringV2 other)
{
if ((this.hash == string.Empty) & ( other.hash == string.Empty))
{
this.GenerateHash();
other.GenerateHash();
}
else if ((this.hash == string.Empty) & !(other.hash == string.Empty))
{
this.GenerateHash();
}
else if (!(this.hash == string.Empty) & (other.hash == string.Empty))
{
other.GenerateHash();
}
if (this.hash.Equals(other.hash))
{
return true;
}
return false;
}
#endregion
#region IDisposable Members
public void Dispose()
{
secureString.Dispose();
hash = string.Empty;
GC.SuppressFinalize(this);
}
#endregion
}
}