本文整理汇总了C#中BinaryReaderEx.ReadBytes方法的典型用法代码示例。如果您正苦于以下问题:C# BinaryReaderEx.ReadBytes方法的具体用法?C# BinaryReaderEx.ReadBytes怎么用?C# BinaryReaderEx.ReadBytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BinaryReaderEx
的用法示例。
在下文中一共展示了BinaryReaderEx.ReadBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadData
public void LoadData(BinaryReaderEx reader)
{
long pos = reader.BaseStream.Position;
BuildFormat();
reader.BaseStream.Position = pos + this.WaveHeader.FormatHeaderLength;
this.WaveData = reader.ReadBytes(this.WaveHeader.DataLength);
}
示例2: LoadSection
public virtual void LoadSection(BinaryReaderEx reader)
{
this.SectionStart = reader.BaseStream.Position;
this.SectionHeader = new SectionHeader();
this.SectionHeader.Magic = reader.ReadInt64();
this.SectionHeader.Version = reader.ReadInt32();
this.SectionHeader.Unknown2 = reader.ReadInt32();
this.SectionHeader.SectionLength = reader.ReadInt32();
this.SectionHeader.Junk = reader.ReadBytes(28);
}
示例3: LoadData
public override void LoadData(BinaryReaderEx reader)
{
base.LoadData(reader);
long pos = reader.BaseStream.Position;
this.BlockSize = reader.ReadInt32(Endianness.BigEndian);
this.StringOffset = reader.ReadInt32(Endianness.BigEndian);
this.ShaderOffset = reader.ReadInt32(Endianness.BigEndian);
this.Name = reader.ReadNullTerminatedString();
reader.BaseStream.Position = pos + this.ShaderOffset;
this.UnknownData = reader.ReadBytes(16);
this.CompiledShaderLength = reader.ReadInt32(Endianness.BigEndian);
this.Unknown4 = reader.ReadInt32(Endianness.BigEndian);
reader.BaseStream.Position = pos + this.ShaderOffset + 0x20;
this.CompiledShader = reader.ReadBytes(this.CompiledShaderLength);
this.DisplayName = String.Format("File [0x{0:X}]", this.ChunkStart);
}
示例4: LoadBones
private void LoadBones(BinaryReaderEx reader)
{
reader.BaseStream.Position = this.BasePosition;
this.Bones = new List<Skeleton.SkeletonBone>(this.BoneCount);
this.Children = new List<INavigable>(this.BoneCount);
for (var i = 0; i < this.BoneCount; i++)
{
Skeleton.SkeletonBone bone = new Skeleton.SkeletonBone();
bone.Parent = this;
bone.StringIndex = reader.ReadInt32();
bone.Unknown1 = reader.ReadInt32();
bone.Unknown2 = reader.ReadInt32();
bone.Unknown3 = reader.ReadInt32();
bone.Translation.X = reader.ReadSingle();
bone.Translation.Y = reader.ReadSingle();
bone.Translation.Z = reader.ReadSingle();
bone.Rotation.X = reader.ReadSingle();
bone.Rotation.Y = reader.ReadSingle();
bone.Rotation.Z = reader.ReadSingle();
bone.Rotation.W = reader.ReadSingle();
bone.Scale.X = reader.ReadSingle();
bone.Scale.Y = reader.ReadSingle();
bone.Scale.Z = reader.ReadSingle();
bone.ParentBoneIndex = reader.ReadInt32();
bone.ChildBoneIndex = reader.ReadInt32();
bone.SiblingBoneIndex = reader.ReadInt32();
bone.BoneIndex = reader.ReadInt32();
bone.Unknown4 = reader.ReadInt32();
bone.Unknown5 = reader.ReadInt32();
bone.Stuff = reader.ReadBytes(96);
this.Bones.Add(bone);
this.Children.Add(bone);
bone.Name = this.StringTable[bone.StringIndex];
}
}
示例5: Load
/// <summary>
/// Load a KDB file from a stream.
/// </summary>
/// <param name="sSource">Stream to read the data from. Must contain
/// a KDBX stream.</param>
/// <param name="kdbFormat">Format specifier.</param>
/// <param name="slLogger">Status logger (optional).</param>
public void Load(Stream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger)
{
Debug.Assert(sSource != null);
if(sSource == null) throw new ArgumentNullException("sSource");
m_format = kdbFormat;
m_slLogger = slLogger;
HashingStreamEx hashedStream = new HashingStreamEx(sSource, false, null);
UTF8Encoding encNoBom = StrUtil.Utf8;
try
{
BinaryReaderEx br = null;
BinaryReaderEx brDecrypted = null;
Stream readerStream = null;
if(kdbFormat == KdbxFormat.Default)
{
br = new BinaryReaderEx(hashedStream, encNoBom, KLRes.FileCorrupted);
ReadHeader(br);
Stream sDecrypted = AttachStreamDecryptor(hashedStream);
if((sDecrypted == null) || (sDecrypted == hashedStream))
throw new SecurityException(KLRes.CryptoStreamFailed);
brDecrypted = new BinaryReaderEx(sDecrypted, encNoBom, KLRes.FileCorrupted);
byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32);
if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32))
throw new InvalidDataException();
for(int iStart = 0; iStart < 32; ++iStart)
{
if(pbStoredStartBytes[iStart] != m_pbStreamStartBytes[iStart])
throw new InvalidCompositeKeyException();
}
Stream sHashed = new HashedBlockStream(sDecrypted, false, 0,
!m_bRepairMode);
if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
readerStream = new GZipStream(sHashed, CompressionMode.Decompress);
else readerStream = sHashed;
}
else if(kdbFormat == KdbxFormat.PlainXml)
readerStream = hashedStream;
else { Debug.Assert(false); throw new FormatException("KdbFormat"); }
if(kdbFormat != KdbxFormat.PlainXml) // Is an encrypted format
{
if(m_pbProtectedStreamKey == null)
{
Debug.Assert(false);
throw new SecurityException("Invalid protected stream key!");
}
m_randomStream = new CryptoRandomStream(m_craInnerRandomStream,
m_pbProtectedStreamKey);
}
else m_randomStream = null; // No random stream for plain-text files
#if KeePassDebug_WriteXml
// FileStream fsOut = new FileStream("Raw.xml", FileMode.Create,
// FileAccess.Write, FileShare.None);
// try
// {
// while(true)
// {
// int b = readerStream.ReadByte();
// if(b == -1) break;
// fsOut.WriteByte((byte)b);
// }
// }
// catch(Exception) { }
// fsOut.Close();
#endif
ReadXmlStreamed(readerStream, hashedStream);
// ReadXmlDom(readerStream);
readerStream.Close();
// GC.KeepAlive(br);
// GC.KeepAlive(brDecrypted);
}
catch(CryptographicException) // Thrown on invalid padding
{
throw new CryptographicException(KLRes.FileCorrupted);
}
finally { CommonCleanUpRead(sSource, hashedStream); }
}
示例6: ReadHeader
private void ReadHeader(BinaryReaderEx br)
{
Debug.Assert(br != null);
if(br == null) throw new ArgumentNullException("br");
byte[] pbSig1 = br.ReadBytes(4);
uint uSig1 = MemUtil.BytesToUInt32(pbSig1);
byte[] pbSig2 = br.ReadBytes(4);
uint uSig2 = MemUtil.BytesToUInt32(pbSig2);
ValidateFileFormat(uSig1, uSig2);
byte[] pb = br.ReadBytes(4);
uint uVersion = MemUtil.BytesToUInt32(pb);
ValidateVersion(uVersion);
while(true)
{
if(ReadHeaderField(br) == false)
break;
}
}
示例7: LoadSection
public override void LoadSection(BinaryReaderEx reader)
{
base.LoadSection(reader);
this.NumEntries = reader.ReadInt16(Endianness.BigEndian);
this.EntryLength = reader.ReadInt16(Endianness.BigEndian);
this.ValuesPerEntry = reader.ReadInt16(Endianness.BigEndian);
this.EquipParams = new List<EquipParam>(this.NumEntries);
this.ValueLengths = new byte[this.ValuesPerEntry];
for (var i = 0; i < this.ValuesPerEntry; i++)
{
this.ValueLengths[i] = reader.ReadByte();
}
for (var p = 0; p < this.NumEntries; p++)
{
var param = new EquipParam();
param.ID = p + 1;
var paramData = reader.ReadBytes(this.EntryLength);
int offset = 0;
byte thisByte = paramData[offset];
int bitCnt = 8;
for (var v = 0; v < this.ValuesPerEntry; v++)
{
int thisLen = this.ValueLengths[v];
int val = 0;
do
{
val <<= 1;
if ((thisByte & 0x80) != 0)
{
val |= 1;
}
thisByte <<= 1;
bitCnt--;
if (bitCnt == 0)
{
offset++;
thisByte = paramData[offset];
bitCnt = 8;
}
thisLen--;
} while (thisLen != 0);
param.Values[v] = val;
}
this.EquipParams.Add(param);
}
}
示例8: ReadHeader
private void ReadHeader(BinaryReaderEx br)
{
Debug.Assert(br != null);
if(br == null) throw new ArgumentNullException("br");
byte[] pbSig1 = br.ReadBytes(4);
uint uSig1 = MemUtil.BytesToUInt32(pbSig1);
byte[] pbSig2 = br.ReadBytes(4);
uint uSig2 = MemUtil.BytesToUInt32(pbSig2);
if((uSig1 == FileSignatureOld1) && (uSig2 == FileSignatureOld2))
throw new OldFormatException(PwDefs.ShortProductName + @" 1.x",
OldFormatException.OldFormatType.KeePass1x);
if((uSig1 == FileSignature1) && (uSig2 == FileSignature2)) { }
else if((uSig1 == FileSignaturePreRelease1) && (uSig2 ==
FileSignaturePreRelease2)) { }
else throw new FormatException(KLRes.FileSigInvalid);
byte[] pb = br.ReadBytes(4);
uint uVersion = MemUtil.BytesToUInt32(pb);
if((uVersion & FileVersionCriticalMask) > (FileVersion32 & FileVersionCriticalMask))
throw new FormatException(KLRes.FileVersionUnsupported +
MessageService.NewParagraph + KLRes.FileNewVerReq);
while(true)
{
if(ReadHeaderField(br) == false)
break;
}
}
示例9: ReadHeaderField
private bool ReadHeaderField(BinaryReaderEx brSource)
{
Debug.Assert(brSource != null);
if(brSource == null) throw new ArgumentNullException("brSource");
byte btFieldID = brSource.ReadByte();
int cbSize;
Debug.Assert(m_uFileVersion > 0);
if(m_uFileVersion < FileVersion32_4)
cbSize = (int)MemUtil.BytesToUInt16(brSource.ReadBytes(2));
else cbSize = MemUtil.BytesToInt32(brSource.ReadBytes(4));
if(cbSize < 0) throw new FormatException(KLRes.FileCorrupted);
byte[] pbData = MemUtil.EmptyByteArray;
if(cbSize > 0) pbData = brSource.ReadBytes(cbSize);
bool bResult = true;
KdbxHeaderFieldID kdbID = (KdbxHeaderFieldID)btFieldID;
switch(kdbID)
{
case KdbxHeaderFieldID.EndOfHeader:
bResult = false; // Returning false indicates end of header
break;
case KdbxHeaderFieldID.CipherID:
SetCipher(pbData);
break;
case KdbxHeaderFieldID.CompressionFlags:
SetCompressionFlags(pbData);
break;
case KdbxHeaderFieldID.MasterSeed:
m_pbMasterSeed = pbData;
CryptoRandom.Instance.AddEntropy(pbData);
break;
// Obsolete; for backward compatibility only
case KdbxHeaderFieldID.TransformSeed:
Debug.Assert(m_uFileVersion < FileVersion32_4);
AesKdf kdfS = new AesKdf();
if(!m_pwDatabase.KdfParameters.KdfUuid.Equals(kdfS.Uuid))
m_pwDatabase.KdfParameters = kdfS.GetDefaultParameters();
// m_pbTransformSeed = pbData;
m_pwDatabase.KdfParameters.SetByteArray(AesKdf.ParamSeed, pbData);
CryptoRandom.Instance.AddEntropy(pbData);
break;
// Obsolete; for backward compatibility only
case KdbxHeaderFieldID.TransformRounds:
Debug.Assert(m_uFileVersion < FileVersion32_4);
AesKdf kdfR = new AesKdf();
if(!m_pwDatabase.KdfParameters.KdfUuid.Equals(kdfR.Uuid))
m_pwDatabase.KdfParameters = kdfR.GetDefaultParameters();
// m_pwDatabase.KeyEncryptionRounds = MemUtil.BytesToUInt64(pbData);
m_pwDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds,
MemUtil.BytesToUInt64(pbData));
break;
case KdbxHeaderFieldID.EncryptionIV:
m_pbEncryptionIV = pbData;
break;
case KdbxHeaderFieldID.InnerRandomStreamKey:
Debug.Assert(m_uFileVersion < FileVersion32_4);
Debug.Assert(m_pbInnerRandomStreamKey == null);
m_pbInnerRandomStreamKey = pbData;
CryptoRandom.Instance.AddEntropy(pbData);
break;
case KdbxHeaderFieldID.StreamStartBytes:
Debug.Assert(m_uFileVersion < FileVersion32_4);
m_pbStreamStartBytes = pbData;
break;
case KdbxHeaderFieldID.InnerRandomStreamID:
Debug.Assert(m_uFileVersion < FileVersion32_4);
SetInnerRandomStreamID(pbData);
break;
case KdbxHeaderFieldID.KdfParameters:
m_pwDatabase.KdfParameters = KdfParameters.DeserializeExt(pbData);
break;
case KdbxHeaderFieldID.PublicCustomData:
Debug.Assert(m_pwDatabase.PublicCustomData.Count == 0);
m_pwDatabase.PublicCustomData = VariantDictionary.Deserialize(pbData);
break;
default:
Debug.Assert(false);
if(m_slLogger != null)
m_slLogger.SetText(KLRes.UnknownHeaderId + @": " +
kdbID.ToString() + "!", LogStatusType.Warning);
//.........这里部分代码省略.........
示例10: CreateQuaternionCurve
private static Curves.QuaternionCurve CreateQuaternionCurve(BinaryReaderEx reader, short count)
{
var result = new Curves.QuaternionCurve();
bool flag = (count & 0x80) != 0;
int numLengths = count & 0xFF7F;
var lengths = reader.ReadBytes(numLengths);
// Lengths section is always a multiple of 4-bytes in length, so advance the stream past the unused bytes
var unusedBytes = ((numLengths + 3) & 0x7FFFFFFC) - numLengths;
reader.BaseStream.Position += unusedBytes;
for (var i = 0; i < numLengths; i++)
{
byte len = lengths[i];
for (var j = 0; j < len; j++)
{
long data = 0;
data = (long)reader.ReadUInt16(Endianness.BigEndian) << 32;
data |= (long)reader.ReadUInt16(Endianness.BigEndian) << 16;
data |= (long)reader.ReadUInt16(Endianness.BigEndian);
int index = (int)(data >> 43) & 0x1F; // 5-bit index of this quaternion
int signFlags = (int)(data >> 39) & 0x0F; // 4-bit sign Flags
int val = (int)(data >> 17) & 0x3FFFFF; // 22-bit integer
int wVal = (int)(data & 0x1FFFF); // 17-bit integer
int globalIdx = index + 32 * i;
float w = (float)wVal / 131071.0f;
if (flag)
{
w = 1 - w * w;
}
double halfPi = Math.PI * 0.5;
double dVal = (double)val;
double sqrtVal = Math.Sqrt(dVal);
double sqrtValWholePart = Math.Truncate(sqrtVal);
double v44 = halfPi * (1 - (sqrtValWholePart / 2047));
double tmp = (sqrtValWholePart < 0.001) ? 0 : halfPi * (dVal - sqrtValWholePart * sqrtValWholePart) / (2 * sqrtValWholePart);
double tmp6 = Math.Sqrt(1 - w * w);
double tX = Math.Sin(-tmp);
double tY = Math.Sin(halfPi - tmp);
double tZ = Math.Sin(v44);
double tW = Math.Sin(v44 - halfPi);
float rX = (float)(tY * -tW * tmp6);
float rY = (float)(tZ * tmp6);
float rZ = (float)(-tX * -tW * tmp6);
SlimDX.Quaternion qValue = new SlimDX.Quaternion();
if ((signFlags & 0x8) != 0)
{
signFlags ^= 0xF; // Switch all the bits
qValue.W = -w;
}
else
{
qValue.W = w;
}
// Flag Set means Negate
qValue.X = ((signFlags & 0x4) != 0) ? -rX : rX;
qValue.Y = ((signFlags & 0x2) != 0) ? -rY : rY;
qValue.Z = ((signFlags & 0x1) != 0) ? -rZ : rZ;
qValue.Normalize();
var curveValue = new Curves.QuaternionCurveValue()
{
Time = (float)globalIdx,
Value = qValue
};
result.Values.Add(curveValue);
}
}
return result;
}
示例11: CreateCompressedLinearCurve
private static Curves.LinearCurve CreateCompressedLinearCurve(BinaryReaderEx reader, AnimatedComponent component, short count)
{
var result = new Curves.LinearCurve(component);
bool flag = (count & 0x8000) != 0;
int numValues = count & 0x7FFF;
float offset = reader.ReadSingle(Endianness.BigEndian);
float scale = reader.ReadSingle(Endianness.BigEndian);
var lengths = reader.ReadBytes(numValues);
for (var i = 0; i < numValues; i++)
{
var length = lengths[i];
if (length == 0) { length = 1; }
var indices = reader.ReadBytes(length);
if (flag)
{
for (var j = 0; j < length; j++)
{
ushort sval = reader.ReadUInt16(Endianness.BigEndian);
bool isNeg = (sval & 0x8000) != 0;
float val = (sval & 0x7FFF) / 32767.0f;
if (isNeg) { val = -val; }
val = val * scale + offset;
Curves.LinearCurveValue curveVal = new Curves.LinearCurveValue()
{
Time = (float)(indices[j] + 256*i),
Value = val
};
result.Values.Add(curveVal);
}
}
else
{
for (var j = 0; j < length; j++)
{
byte sval = reader.ReadByte();
bool isNeg = (sval & 0x80) != 0;
float val = (sval & 0x7F) / 127.0f;
if (isNeg) { val = -val; }
val = val * scale + offset;
Curves.LinearCurveValue curveVal = new Curves.LinearCurveValue()
{
Time = (float)(indices[j] + 256 * i),
Value = val
};
result.Values.Add(curveVal);
}
}
}
// Align reader position to 4-byte boundary
reader.BaseStream.Position = (reader.BaseStream.Position + 3) & 0x7FFFFFFFFFFFFFFC;
return result;
}
示例12: LoadTextureData
public void LoadTextureData(BinaryReaderEx reader)
{
this.TextureData = new List<byte[]>(this.Header.MipMapCount);
foreach (MipMapData mipData in this.MipMapData)
{
reader.BaseStream.Position = this.DataOffset + mipData.Offset;
this.TextureData.Add(reader.ReadBytes(mipData.Length));
}
}
示例13: Load
/// <summary>
/// Load a KDB file from a stream.
/// </summary>
/// <param name="sSource">Stream to read the data from. Must contain
/// a KDBX stream.</param>
/// <param name="kdbFormat">Format specifier.</param>
/// <param name="slLogger">Status logger (optional).</param>
public void Load(Stream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger)
{
Debug.Assert(sSource != null);
if(sSource == null) throw new ArgumentNullException("sSource");
m_format = kdbFormat;
m_slLogger = slLogger;
HashingStreamEx hashedStream = new HashingStreamEx(sSource, false, null);
UTF8Encoding encNoBom = StrUtil.Utf8;
try
{
BinaryReaderEx br = null;
BinaryReaderEx brDecrypted = null;
Stream readerStream = null;
if(kdbFormat == KdbxFormat.Default || kdbFormat == KdbxFormat.ProtocolBuffers)
{
br = new BinaryReaderEx(hashedStream, encNoBom, KLRes.FileCorrupted);
ReadHeader(br);
Stream sDecrypted = AttachStreamDecryptor(hashedStream);
if((sDecrypted == null) || (sDecrypted == hashedStream))
throw new SecurityException(KLRes.CryptoStreamFailed);
if (m_slLogger != null)
m_slLogger.SetText("KP2AKEY_TransformingKey", LogStatusType.AdditionalInfo);
brDecrypted = new BinaryReaderEx(sDecrypted, encNoBom, KLRes.FileCorrupted);
byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32);
if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32))
throw new InvalidDataException();
if (m_slLogger != null)
m_slLogger.SetText("KP2AKEY_DecodingDatabase", LogStatusType.AdditionalInfo);
for(int iStart = 0; iStart < 32; ++iStart)
{
if(pbStoredStartBytes[iStart] != m_pbStreamStartBytes[iStart])
throw new InvalidCompositeKeyException();
}
Stream sHashed = new HashedBlockStream(sDecrypted, false, 0,
!m_bRepairMode);
if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
readerStream = new Ionic.Zlib.GZipStream(sHashed, Ionic.Zlib.CompressionMode.Decompress);
else readerStream = sHashed;
}
else if(kdbFormat == KdbxFormat.PlainXml)
readerStream = hashedStream;
else { Debug.Assert(false); throw new FormatException("KdbFormat"); }
if(kdbFormat != KdbxFormat.PlainXml) // Is an encrypted format
{
if(m_pbProtectedStreamKey == null)
{
Debug.Assert(false);
throw new SecurityException("Invalid protected stream key!");
}
m_randomStream = new CryptoRandomStream(m_craInnerRandomStream,
m_pbProtectedStreamKey);
}
else m_randomStream = null; // No random stream for plain-text files
if (m_slLogger != null)
m_slLogger.SetText("KP2AKEY_ParsingDatabase", LogStatusType.AdditionalInfo);
var stopWatch = Stopwatch.StartNew();
if (kdbFormat == KdbxFormat.ProtocolBuffers)
{
KdbpFile.ReadDocument(m_pwDatabase, readerStream, m_pbProtectedStreamKey, m_pbHashOfHeader);
Kp2aLog.Log(String.Format("KdbpFile.ReadDocument: {0}ms", stopWatch.ElapsedMilliseconds));
}
else
{
ReadXmlStreamed(readerStream, hashedStream);
Kp2aLog.Log(String.Format("ReadXmlStreamed: {0}ms", stopWatch.ElapsedMilliseconds));
}
readerStream.Close();
// GC.KeepAlive(br);
// GC.KeepAlive(brDecrypted);
}
catch(CryptographicException) // Thrown on invalid padding
{
throw new CryptographicException(KLRes.FileCorrupted);
}
//.........这里部分代码省略.........
示例14: Load
/// <summary>
/// Load a KDBX file from a stream.
/// </summary>
/// <param name="sSource">Stream to read the data from. Must contain
/// a KDBX stream.</param>
/// <param name="fmt">Format.</param>
/// <param name="slLogger">Status logger (optional).</param>
public void Load(Stream sSource, KdbxFormat fmt, IStatusLogger slLogger)
{
Debug.Assert(sSource != null);
if(sSource == null) throw new ArgumentNullException("sSource");
if(m_bUsedOnce)
throw new InvalidOperationException("Do not reuse KdbxFile objects!");
m_bUsedOnce = true;
#if KDBX_BENCHMARK
Stopwatch swTime = Stopwatch.StartNew();
#endif
m_format = fmt;
m_slLogger = slLogger;
m_pbsBinaries.Clear();
UTF8Encoding encNoBom = StrUtil.Utf8;
byte[] pbCipherKey = null;
byte[] pbHmacKey64 = null;
List<Stream> lStreams = new List<Stream>();
lStreams.Add(sSource);
HashingStreamEx sHashing = new HashingStreamEx(sSource, false, null);
lStreams.Add(sHashing);
try
{
Stream sXml;
if(fmt == KdbxFormat.Default)
{
BinaryReaderEx br = new BinaryReaderEx(sHashing,
encNoBom, KLRes.FileCorrupted);
byte[] pbHeader = LoadHeader(br);
m_pbHashOfHeader = CryptoUtil.HashSha256(pbHeader);
int cbEncKey, cbEncIV;
ICipherEngine iCipher = GetCipher(out cbEncKey, out cbEncIV);
ComputeKeys(out pbCipherKey, cbEncKey, out pbHmacKey64);
string strIncomplete = KLRes.FileHeaderCorrupted + " " +
KLRes.FileIncomplete;
Stream sPlain;
if(m_uFileVersion < FileVersion32_4)
{
Stream sDecrypted = EncryptStream(sHashing, iCipher,
pbCipherKey, cbEncIV, false);
if((sDecrypted == null) || (sDecrypted == sHashing))
throw new SecurityException(KLRes.CryptoStreamFailed);
lStreams.Add(sDecrypted);
BinaryReaderEx brDecrypted = new BinaryReaderEx(sDecrypted,
encNoBom, strIncomplete);
byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32);
if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32))
throw new EndOfStreamException(strIncomplete);
if(!MemUtil.ArraysEqual(pbStoredStartBytes, m_pbStreamStartBytes))
throw new InvalidCompositeKeyException();
sPlain = new HashedBlockStream(sDecrypted, false, 0, !m_bRepairMode);
}
else // KDBX >= 4
{
byte[] pbStoredHash = MemUtil.Read(sHashing, 32);
if((pbStoredHash == null) || (pbStoredHash.Length != 32))
throw new EndOfStreamException(strIncomplete);
if(!MemUtil.ArraysEqual(m_pbHashOfHeader, pbStoredHash))
throw new InvalidDataException(KLRes.FileHeaderCorrupted);
byte[] pbHeaderHmac = ComputeHeaderHmac(pbHeader, pbHmacKey64);
byte[] pbStoredHmac = MemUtil.Read(sHashing, 32);
if((pbStoredHmac == null) || (pbStoredHmac.Length != 32))
throw new EndOfStreamException(strIncomplete);
if(!MemUtil.ArraysEqual(pbHeaderHmac, pbStoredHmac))
throw new InvalidCompositeKeyException();
HmacBlockStream sBlocks = new HmacBlockStream(sHashing,
false, !m_bRepairMode, pbHmacKey64);
lStreams.Add(sBlocks);
sPlain = EncryptStream(sBlocks, iCipher, pbCipherKey,
cbEncIV, false);
if((sPlain == null) || (sPlain == sBlocks))
throw new SecurityException(KLRes.CryptoStreamFailed);
}
lStreams.Add(sPlain);
if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
//.........这里部分代码省略.........
示例15: ReadInnerHeaderField
private bool ReadInnerHeaderField(BinaryReaderEx br)
{
Debug.Assert(br != null);
if(br == null) throw new ArgumentNullException("br");
byte btFieldID = br.ReadByte();
int cbSize = MemUtil.BytesToInt32(br.ReadBytes(4));
if(cbSize < 0) throw new FormatException(KLRes.FileCorrupted);
byte[] pbData = MemUtil.EmptyByteArray;
if(cbSize > 0) pbData = br.ReadBytes(cbSize);
bool bResult = true;
KdbxInnerHeaderFieldID kdbID = (KdbxInnerHeaderFieldID)btFieldID;
switch(kdbID)
{
case KdbxInnerHeaderFieldID.EndOfHeader:
bResult = false; // Returning false indicates end of header
break;
case KdbxInnerHeaderFieldID.InnerRandomStreamID:
SetInnerRandomStreamID(pbData);
break;
case KdbxInnerHeaderFieldID.InnerRandomStreamKey:
Debug.Assert(m_pbInnerRandomStreamKey == null);
m_pbInnerRandomStreamKey = pbData;
CryptoRandom.Instance.AddEntropy(pbData);
break;
case KdbxInnerHeaderFieldID.Binary:
if(pbData.Length < 1) throw new FormatException();
KdbxBinaryFlags f = (KdbxBinaryFlags)pbData[0];
bool bProt = ((f & KdbxBinaryFlags.Protected) != KdbxBinaryFlags.None);
ProtectedBinary pb = new ProtectedBinary(bProt, pbData,
1, pbData.Length - 1);
m_pbsBinaries.Add(pb);
if(bProt) MemUtil.ZeroByteArray(pbData);
break;
default:
Debug.Assert(false);
break;
}
return bResult;
}