private int GenerateInternal(byte b, byte[] salt, ref bool isSaltEncrypted, bool doNotEncrypt = false) { var byteBuffer = new byte[salt.Length + 1]; try { //Decrypt salt if (isSaltEncrypted) { _memoryProtector.Unprotect(salt); isSaltEncrypted = false; } //Append salt + byte Array.Copy(salt, byteBuffer, salt.Length); byteBuffer[salt.Length] = b; //Hash it var result = _fastHasher.ComputeFast(byteBuffer); return(result); } finally { Array.Clear(byteBuffer, 0, byteBuffer.Length); //Encrypt the salt if (!isSaltEncrypted && !doNotEncrypt) { _memoryProtector.Protect(salt); isSaltEncrypted = true; } } }
/// <summary> /// Appends the specified <see cref="ISafeByte" /> instance to the inner encrypted collection. /// </summary> /// <param name="safeByte">The safe byte.</param> /// <exception cref="System.ArgumentNullException"><paramref name="safeByte" /> is <see langword="null" />.</exception> /// <exception cref="ObjectDisposedException">Throws if the <see cref="EncryptedSafeByteCollection" /> instance is disposed</exception> /// <seealso cref="ISafeByte" /> public void Append(ISafeByte safeByte) { EnsureNotDisposed(); if (safeByte == null) { throw new ArgumentNullException(nameof(safeByte)); } _memoryProtector.Unprotect(_encryptionKey); var list = DecryptAndDeserialize(_encryptedCollection, _encryptionKey); list.Add(safeByte.Id); _encryptedCollection = SerializeAndEncrypt(list, _encryptionKey); list.Clear(); _memoryProtector.Protect(_encryptionKey); Length++; }
/// <summary> /// Decrypts and returns the byte that this <see cref="SafeByte" /> instance represents. /// </summary> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Thrown when byte is not set</exception> public byte Get() { EnsureByteIsSet(); byte[] byteBuffer = null; try { _memoryProtector.Unprotect(_encryptionKey); _memoryProtector.Unprotect(_encryptedByte); var encryptedBuffer = new byte[_encryptedByteLength]; try { Buffer.BlockCopy(_encryptedByte, 0, encryptedBuffer, 0, _encryptedByteLength); byteBuffer = _encryptor.Decrypt(encryptedBuffer, _encryptionKey); //Extract the byte from arbitrary bytes return(byteBuffer[_realBytePosition]); } finally { Array.Clear(encryptedBuffer, 0, _encryptedByteLength); } } finally { if (byteBuffer != null) { Array.Clear(byteBuffer, 0, byteBuffer.Length); } _memoryProtector.Protect(_encryptionKey); _memoryProtector.Protect(_encryptedByte); } }