Rename Util class to Utilities

Preparation to split it up into the Util namespace and to add nn::util code
This commit is contained in:
Alex Barney 2020-06-27 17:39:52 -07:00
parent 88983d39e5
commit b6eac5ddb5
43 changed files with 116 additions and 116 deletions

View File

@ -25,14 +25,14 @@ namespace LibHac.Crypto.Detail
public void Transform(ReadOnlySpan<byte> input, Span<byte> output)
{
int blockCount = Util.DivideByRoundUp(input.Length, Aes.BlockSize);
int blockCount = Utilities.DivideByRoundUp(input.Length, Aes.BlockSize);
int length = blockCount * Aes.BlockSize;
using var counterBuffer = new RentedArray<byte>(length);
FillDecryptedCounter(Iv, counterBuffer.Span);
_aesCore.Encrypt(counterBuffer.Array, counterBuffer.Array, length);
Util.XorArrays(output, input, counterBuffer.Span);
Utilities.XorArrays(output, input, counterBuffer.Span);
}
private static void FillDecryptedCounter(Span<byte> counter, Span<byte> buffer)

View File

@ -115,7 +115,7 @@ namespace LibHac.Crypto.Detail
_aesCore.Encrypt(counter, counter);
input.CopyTo(output);
Util.XorArrays(output, counter);
Utilities.XorArrays(output, counter);
for (int i = 0; i < counter.Length; i++)
{

View File

@ -43,9 +43,9 @@ namespace LibHac.Crypto.Detail
using var tweakBuffer = new RentedArray<byte>(blockCount * Aes.BlockSize);
tweak = FillTweakBuffer(tweak, MemoryMarshal.Cast<byte, Buffer16>(tweakBuffer.Span));
Util.XorArrays(output, input, tweakBuffer.Span);
Utilities.XorArrays(output, input, tweakBuffer.Span);
_dataAesCore.Encrypt(output.Slice(0, blockCount * Aes.BlockSize), output);
Util.XorArrays(output, output, tweakBuffer.Array);
Utilities.XorArrays(output, output, tweakBuffer.Array);
if (leftover != 0)
{
@ -97,9 +97,9 @@ namespace LibHac.Crypto.Detail
using var tweakBuffer = new RentedArray<byte>(blockCount * Aes.BlockSize);
tweak = FillTweakBuffer(tweak, MemoryMarshal.Cast<byte, Buffer16>(tweakBuffer.Span));
Util.XorArrays(output, input, tweakBuffer.Span);
Utilities.XorArrays(output, input, tweakBuffer.Span);
_dataAesCore.Decrypt(output.Slice(0, blockCount * Aes.BlockSize), output);
Util.XorArrays(output, output, tweakBuffer.Span);
Utilities.XorArrays(output, output, tweakBuffer.Span);
}
if (leftover != 0)

View File

@ -132,7 +132,7 @@ namespace LibHac
byte[] testEnc = rsa.Encrypt(test, false);
byte[] testDec = rsa.Decrypt(testEnc, false);
if (!Util.ArraysEqual(test, testDec))
if (!Utilities.ArraysEqual(test, testDec))
{
throw new InvalidDataException("Could not verify RSA key pair");
}

View File

@ -101,7 +101,7 @@ namespace LibHac.Fs
if (queryRc.IsFailure()) return queryRc;
requiredSizeSum += Util.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
requiredSizeSum += Utilities.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
}
}
else
@ -118,7 +118,7 @@ namespace LibHac.Fs
if (queryRc.IsFailure()) return queryRc;
requiredSizeSum += Util.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
requiredSizeSum += Utilities.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
}
else if (ResultFs.PathAlreadyExists.Includes(createRc))
{
@ -162,7 +162,7 @@ namespace LibHac.Fs
Result queryRc = fs.QuerySaveDataTotalSize(out long totalSize, dataSize, journalSize);
if (queryRc.IsFailure()) return queryRc;
requiredSize += Util.AlignUp(totalSize, 0x4000) + baseSize;
requiredSize += Utilities.AlignUp(totalSize, 0x4000) + baseSize;
}
else if (!ResultFs.PathAlreadyExists.Includes(rc))
{

View File

@ -36,7 +36,7 @@ namespace LibHac.FsSystem
public int TransformBlock(Span<byte> data)
{
int blockCount = Util.DivideByRoundUp(data.Length, BlockSizeBytes);
int blockCount = Utilities.DivideByRoundUp(data.Length, BlockSizeBytes);
int length = blockCount * BlockSizeBytes;
byte[] counterXor = ArrayPool<byte>.Shared.Rent(length);
@ -46,7 +46,7 @@ namespace LibHac.FsSystem
FillDecryptedCounter(counterXor.AsSpan(0, length));
_encryptor.TransformBlock(counterXor, 0, length, counterXor, 0);
Util.XorArrays(data, counterXor);
Utilities.XorArrays(data, counterXor);
}
finally
{

View File

@ -83,7 +83,7 @@ namespace LibHac.FsSystem
/* get number of blocks */
int m = count >> 4;
int mo = count & 15;
int alignedCount = Util.AlignUp(count, BlockSizeBytes);
int alignedCount = Utilities.AlignUp(count, BlockSizeBytes);
/* for i = 0 to m-2 do */
if (mo == 0)
@ -103,9 +103,9 @@ namespace LibHac.FsSystem
if (lim > 0)
{
Util.XorArrays(buffer.AsSpan(offset, lim * 16), tweak);
Utilities.XorArrays(buffer.AsSpan(offset, lim * 16), tweak);
_key1.TransformBlock(buffer, offset, lim * 16, buffer, offset);
Util.XorArrays(buffer.AsSpan(offset, lim * 16), tweak);
Utilities.XorArrays(buffer.AsSpan(offset, lim * 16), tweak);
}
if (mo > 0)

View File

@ -38,7 +38,7 @@ namespace LibHac.FsSystem
}
else
{
string entryName = Util.GetUtf8StringNullTerminated(entry.Name);
string entryName = Utilities.GetUtf8StringNullTerminated(entry.Name);
entry.Size = GetAesXtsFileSize(PathTools.Combine(Path.ToString(), entryName).ToU8Span());
}
}

View File

@ -37,12 +37,12 @@ namespace LibHac.FsSystem
ThrowHelper.ThrowResult(ResultFs.AesXtsFileHeaderInvalidKeys.Value, "NAX0 key derivation failed.");
}
if (HeaderLength + Util.AlignUp(Header.Size, 0x10) > fileSize)
if (HeaderLength + Utilities.AlignUp(Header.Size, 0x10) > fileSize)
{
ThrowHelper.ThrowResult(ResultFs.AesXtsFileTooShort.Value, "NAX0 key derivation failed.");
}
IStorage encStorage = BaseFile.AsStorage().Slice(HeaderLength, Util.AlignUp(Header.Size, 0x10));
IStorage encStorage = BaseFile.AsStorage().Slice(HeaderLength, Utilities.AlignUp(Header.Size, 0x10));
BaseStorage = new CachedStorage(new Aes128XtsStorage(encStorage, Header.DecryptedKey1, Header.DecryptedKey2, BlockSize, true), 4, true);
}
@ -115,7 +115,7 @@ namespace LibHac.FsSystem
Result rc = BaseFile.Write(0, Header.ToBytes(false));
if (rc.IsFailure()) return rc;
return BaseStorage.SetSize(Util.AlignUp(size, 0x10));
return BaseStorage.SetSize(Utilities.AlignUp(size, 0x10));
}
protected override void Dispose(bool disposing)

View File

@ -68,7 +68,7 @@ namespace LibHac.FsSystem
DecryptKeys();
byte[] hmac = CalculateHmac(verificationKey);
return Util.ArraysEqual(hmac, Signature);
return Utilities.ArraysEqual(hmac, Signature);
}
public void SetSize(long size, byte[] verificationKey)

View File

@ -50,7 +50,7 @@ namespace LibHac.FsSystem
/// <param name="key">The 256-bit key containing a 128-bit data key followed by a 128-bit tweak key.</param>
public Result CreateFile(U8Span path, long size, CreateFileOptions options, byte[] key)
{
long containerSize = AesXtsFile.HeaderLength + Util.AlignUp(size, 0x10);
long containerSize = AesXtsFile.HeaderLength + Utilities.AlignUp(size, 0x10);
Result rc = BaseFileSystem.CreateFile(path, containerSize, options);
if (rc.IsFailure()) return rc;

View File

@ -37,7 +37,7 @@ namespace LibHac.FsSystem
Assert.AssertTrue(entrySize >= sizeof(long));
Assert.AssertTrue(nodeSize >= entrySize + Unsafe.SizeOf<NodeHeader>());
Assert.AssertTrue(NodeSizeMin <= nodeSize && nodeSize <= NodeSizeMax);
Assert.AssertTrue(Util.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(Utilities.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(!IsInitialized());
// Ensure valid entry count.
@ -139,7 +139,7 @@ namespace LibHac.FsSystem
Assert.AssertTrue(entrySize >= sizeof(long));
Assert.AssertTrue(nodeSize >= entrySize + Unsafe.SizeOf<NodeHeader>());
Assert.AssertTrue(NodeSizeMin <= nodeSize && nodeSize <= NodeSizeMax);
Assert.AssertTrue(Util.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(Utilities.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(entryCount >= 0);
if (entryCount <= 0)
@ -153,7 +153,7 @@ namespace LibHac.FsSystem
Assert.AssertTrue(entrySize >= sizeof(long));
Assert.AssertTrue(nodeSize >= entrySize + Unsafe.SizeOf<NodeHeader>());
Assert.AssertTrue(NodeSizeMin <= nodeSize && nodeSize <= NodeSizeMax);
Assert.AssertTrue(Util.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(Utilities.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(entryCount >= 0);
if (entryCount <= 0)
@ -175,7 +175,7 @@ namespace LibHac.FsSystem
private static int GetEntrySetCount(long nodeSize, long entrySize, int entryCount)
{
int entryCountPerNode = GetEntryCount(nodeSize, entrySize);
return Util.DivideByRoundUp(entryCount, entryCountPerNode);
return Utilities.DivideByRoundUp(entryCount, entryCountPerNode);
}
public static int GetNodeL2Count(long nodeSize, long entrySize, int entryCount)
@ -186,10 +186,10 @@ namespace LibHac.FsSystem
if (entrySetCount <= offsetCountPerNode)
return 0;
int nodeL2Count = Util.DivideByRoundUp(entrySetCount, offsetCountPerNode);
int nodeL2Count = Utilities.DivideByRoundUp(entrySetCount, offsetCountPerNode);
Abort.DoAbortUnless(nodeL2Count <= offsetCountPerNode);
return Util.DivideByRoundUp(entrySetCount - (offsetCountPerNode - (nodeL2Count - 1)), offsetCountPerNode);
return Utilities.DivideByRoundUp(entrySetCount - (offsetCountPerNode - (nodeL2Count - 1)), offsetCountPerNode);
}
private static long GetBucketTreeEntryOffset(long entrySetOffset, long entrySize, int entryIndex)

View File

@ -44,7 +44,7 @@ namespace LibHac.FsSystem
Assert.AssertTrue(entrySize >= sizeof(long));
Assert.AssertTrue(nodeSize >= entrySize + Unsafe.SizeOf<NodeHeader>());
Assert.AssertTrue(NodeSizeMin <= nodeSize && nodeSize <= NodeSizeMax);
Assert.AssertTrue(Util.IsPowerOfTwo(nodeSize));
Assert.AssertTrue(Utilities.IsPowerOfTwo(nodeSize));
if (headerStorage is null || nodeStorage is null || entryStorage is null)
return ResultFs.NullptrArgument.Log();
@ -267,7 +267,7 @@ namespace LibHac.FsSystem
if (rc.IsFailure()) return rc;
}
int l2NodeIndex = Util.DivideByRoundUp(CurrentL2OffsetIndex, OffsetsPerNode) - 2;
int l2NodeIndex = Utilities.DivideByRoundUp(CurrentL2OffsetIndex, OffsetsPerNode) - 2;
int indexInL2Node = CurrentL2OffsetIndex % OffsetsPerNode;
// Finalize the current L2 node if needed
@ -291,7 +291,7 @@ namespace LibHac.FsSystem
// L1 count depends on the existence or absence of L2 nodes
if (CurrentL2OffsetIndex == 0)
{
l1NodeHeader.Count = Util.DivideByRoundUp(CurrentEntryIndex, EntriesPerEntrySet);
l1NodeHeader.Count = Utilities.DivideByRoundUp(CurrentEntryIndex, EntriesPerEntrySet);
}
else
{

View File

@ -63,7 +63,7 @@ namespace LibHac.FsSystem
if (!Mode.HasFlag(OpenDirectoryMode.NoFileSize))
{
string entryName = Util.GetUtf8StringNullTerminated(entry.Name);
string entryName = Utilities.GetUtf8StringNullTerminated(entry.Name);
string entryFullPath = PathTools.Combine(_path.ToString(), entryName);
rc = ParentFileSystem.GetConcatenationFileSize(out long fileSize, entryFullPath.ToU8Span());
@ -122,7 +122,7 @@ namespace LibHac.FsSystem
}
else
{
string name = Util.GetUtf8StringNullTerminated(entry.Name);
string name = Utilities.GetUtf8StringNullTerminated(entry.Name);
var fullPath = PathTools.Combine(_path.ToString(), name).ToU8Span();
return ParentFileSystem.IsConcatenationFile(fullPath);

View File

@ -228,7 +228,7 @@ namespace LibHac.FsSystem
if (size == 0) return 1;
return (int)Util.DivideByRoundUp(size, subFileSize);
return (int)Utilities.DivideByRoundUp(size, subFileSize);
}
private static long QuerySubFileSize(int subFileIndex, long totalSize, long subFileSize)

View File

@ -37,7 +37,7 @@ namespace LibHac.FsSystem
var levelData = new IntegrityVerificationStorage(levelInfo[i], Levels[i - 1], integrityCheckLevel, leaveOpen);
levelData.GetSize(out long levelSize).ThrowIfFailure();
int cacheCount = Math.Min((int)Util.DivideByRoundUp(levelSize, levelInfo[i].BlockSize), 4);
int cacheCount = Math.Min((int)Utilities.DivideByRoundUp(levelSize, levelInfo[i].BlockSize), 4);
Levels[i] = new CachedStorage(levelData, cacheCount, leaveOpen);
LevelValidities[i - 1] = levelData.BlockValidities;
@ -145,7 +145,7 @@ namespace LibHac.FsSystem
IntegrityVerificationStorage storage = IntegrityStorages[IntegrityStorages.Length - 1];
long blockSize = storage.SectorSize;
int blockCount = (int)Util.DivideByRoundUp(Length, blockSize);
int blockCount = (int)Utilities.DivideByRoundUp(Length, blockSize);
var buffer = new byte[blockSize];
var result = Validity.Valid;

View File

@ -63,7 +63,7 @@ namespace LibHac.FsSystem
if (Type == IntegrityStorageType.Save)
{
if (Util.IsEmpty(hashBuffer))
if (Utilities.IsEmpty(hashBuffer))
{
destination.Clear();
BlockValidities[blockIndex] = Validity.Valid;
@ -101,7 +101,7 @@ namespace LibHac.FsSystem
byte[] hash = DoHash(dataBuffer, 0, bytesToHash);
Validity validity = Util.SpansEqual(hashBuffer, hash) ? Validity.Valid : Validity.Invalid;
Validity validity = Utilities.SpansEqual(hashBuffer, hash) ? Validity.Valid : Validity.Invalid;
BlockValidities[blockIndex] = validity;
if (validity == Validity.Invalid && integrityCheckLevel == IntegrityCheckLevel.ErrorOnInvalid)
@ -207,7 +207,7 @@ namespace LibHac.FsSystem
long hashPos = i * DigestSize;
HashStorage.Read(hashPos, digest).ThrowIfFailure();
if (!Util.IsEmpty(digest)) continue;
if (!Utilities.IsEmpty(digest)) continue;
int dataOffset = i * SectorSize;
BaseStorage.Fill(SaveDataFileSystem.TrimFillValue, dataOffset, SectorSize);

View File

@ -35,7 +35,7 @@ namespace LibHac.FsSystem
if (!CanReturnEntry(isDir, Mode)) continue;
ReadOnlySpan<byte> name = Util.GetUtf8Bytes(localEntry.Name);
ReadOnlySpan<byte> name = Utilities.GetUtf8Bytes(localEntry.Name);
DirectoryEntryType type = isDir ? DirectoryEntryType.Directory : DirectoryEntryType.File;
long length = isDir ? 0 : ((FileInfo)localEntry).Length;

View File

@ -28,7 +28,7 @@ namespace LibHac.FsSystem.NcaUtils
{
if (index < 0 || index > 3) throw new ArgumentOutOfRangeException(nameof(index));
int keyRevision = Util.GetMasterKeyRevision(Header.KeyGeneration);
int keyRevision = Utilities.GetMasterKeyRevision(Header.KeyGeneration);
byte[] keyAreaKey = Keyset.KeyAreaKeys[keyRevision][Header.KeyAreaKeyIndex];
if (keyAreaKey.IsEmpty())
@ -47,7 +47,7 @@ namespace LibHac.FsSystem.NcaUtils
public byte[] GetDecryptedTitleKey()
{
int keyRevision = Util.GetMasterKeyRevision(Header.KeyGeneration);
int keyRevision = Utilities.GetMasterKeyRevision(Header.KeyGeneration);
byte[] titleKek = Keyset.TitleKeks[keyRevision];
var rightsId = new RightsId(Header.RightsId);
@ -91,7 +91,7 @@ namespace LibHac.FsSystem.NcaUtils
if (!SectionExists(index)) return false;
if (Header.GetFsHeader(index).EncryptionType == NcaEncryptionType.None) return true;
int keyRevision = Util.GetMasterKeyRevision(Header.KeyGeneration);
int keyRevision = Utilities.GetMasterKeyRevision(Header.KeyGeneration);
if (Header.HasRightsId)
{
@ -126,7 +126,7 @@ namespace LibHac.FsSystem.NcaUtils
BaseStorage.GetSize(out long baseSize).ThrowIfFailure();
if (!Util.IsSubRange(offset, size, baseSize))
if (!Utilities.IsSubRange(offset, size, baseSize))
{
throw new InvalidDataException(
$"Section offset (0x{offset:x}) and length (0x{size:x}) fall outside the total NCA length (0x{baseSize:x}).");

View File

@ -103,7 +103,7 @@ namespace LibHac.FsSystem.NcaUtils
var actualHash = new byte[Sha256.DigestSize];
Sha256.GenerateSha256Hash(data, actualHash);
if (Util.ArraysEqual(expectedHash, actualHash)) return Validity.Valid;
if (Utilities.ArraysEqual(expectedHash, actualHash)) return Validity.Valid;
return Validity.Invalid;
}

View File

@ -102,7 +102,7 @@ namespace LibHac.FsSystem.NcaUtils
public Span<byte> RightsId => _header.Span.Slice(NcaHeaderStruct.RightsIdOffset, NcaHeaderStruct.RightsIdSize);
public bool HasRightsId => !Util.IsEmpty(RightsId);
public bool HasRightsId => !Utilities.IsEmpty(RightsId);
private ref NcaSectionEntryStruct GetSectionEntry(int index)
{
@ -167,7 +167,7 @@ namespace LibHac.FsSystem.NcaUtils
Span<byte> actualHash = stackalloc byte[Sha256.DigestSize];
Sha256.GenerateSha256Hash(headerData.Span, actualHash);
if (!Util.SpansEqual(expectedHash, actualHash))
if (!Utilities.SpansEqual(expectedHash, actualHash))
{
throw new InvalidDataException("FS header hash is invalid.");
}

View File

@ -121,7 +121,7 @@ namespace LibHac.FsSystem
size += entry.NameLength + 1;
}
int endOffset = Util.AlignUp(startOffset + size, GetMetaDataAlignment(type));
int endOffset = Utilities.AlignUp(startOffset + size, GetMetaDataAlignment(type));
return endOffset - startOffset;
}

View File

@ -83,7 +83,7 @@ namespace LibHac.FsSystem.RomFs
public bool TryOpenFile(string path, out T fileInfo)
{
FindPathRecursive(Util.GetUtf8Bytes(path), out RomEntryKey key);
FindPathRecursive(Utilities.GetUtf8Bytes(path), out RomEntryKey key);
if (FileTable.TryGetValue(ref key, out RomKeyValuePair<FileRomEntry> keyValuePair))
{
@ -116,7 +116,7 @@ namespace LibHac.FsSystem.RomFs
/// otherwise, <see langword="false"/>.</returns>
public bool TryOpenDirectory(string path, out FindPosition position)
{
FindPathRecursive(Util.GetUtf8Bytes(path), out RomEntryKey key);
FindPathRecursive(Utilities.GetUtf8Bytes(path), out RomEntryKey key);
if (DirectoryTable.TryGetValue(ref key, out RomKeyValuePair<DirectoryRomEntry> keyValuePair))
{
@ -169,7 +169,7 @@ namespace LibHac.FsSystem.RomFs
position.NextFile = entry.NextSibling;
info = entry.Info;
name = Util.GetUtf8String(nameBytes);
name = Utilities.GetUtf8String(nameBytes);
return true;
}
@ -193,7 +193,7 @@ namespace LibHac.FsSystem.RomFs
ref DirectoryRomEntry entry = ref DirectoryTable.GetValueReference(position.NextDirectory, out Span<byte> nameBytes);
position.NextDirectory = entry.NextSibling;
name = Util.GetUtf8String(nameBytes);
name = Utilities.GetUtf8String(nameBytes);
return true;
}
@ -207,7 +207,7 @@ namespace LibHac.FsSystem.RomFs
public void AddFile(string path, ref T fileInfo)
{
path = PathTools.Normalize(path);
ReadOnlySpan<byte> pathBytes = Util.GetUtf8Bytes(path);
ReadOnlySpan<byte> pathBytes = Utilities.GetUtf8Bytes(path);
if (path == "/") throw new ArgumentException("Path cannot be empty");
@ -223,7 +223,7 @@ namespace LibHac.FsSystem.RomFs
{
path = PathTools.Normalize(path);
CreateDirectoryRecursive(Util.GetUtf8Bytes(path));
CreateDirectoryRecursive(Utilities.GetUtf8Bytes(path));
}
/// <summary>

View File

@ -61,7 +61,7 @@ namespace LibHac.FsSystem.RomFs
Sources.Add(fileStorage);
long newOffset = CurrentOffset + fileSize;
CurrentOffset = Util.AlignUp(newOffset, FileAlignment);
CurrentOffset = Utilities.AlignUp(newOffset, FileAlignment);
var padding = new NullStorage(CurrentOffset - newOffset);
Sources.Add(padding);

View File

@ -140,7 +140,7 @@ namespace LibHac.FsSystem.RomFs
private int CreateNewEntry(int nameLength)
{
int bytesNeeded = Util.AlignUp(_sizeOfEntry + nameLength, 4);
int bytesNeeded = Utilities.AlignUp(_sizeOfEntry + nameLength, 4);
if (_length + bytesNeeded > _capacity)
{

View File

@ -104,8 +104,8 @@ namespace LibHac.FsSystem.Save
protected override Result DoSetSize(long size)
{
int oldBlockCount = (int)Util.DivideByRoundUp(_length, BlockSize);
int newBlockCount = (int)Util.DivideByRoundUp(size, BlockSize);
int oldBlockCount = (int)Utilities.DivideByRoundUp(_length, BlockSize);
int newBlockCount = (int)Utilities.DivideByRoundUp(size, BlockSize);
if (oldBlockCount == newBlockCount) return Result.Success;

View File

@ -85,7 +85,7 @@ namespace LibHac.FsSystem.Save
Span<byte> actualHeaderHash = stackalloc byte[Sha256.DigestSize];
Sha256.GenerateSha256Hash(Data.AsSpan(0x300, 0x3d00), actualHeaderHash);
HeaderHashValidity = Util.SpansEqual(Layout.Hash, actualHeaderHash) ? Validity.Valid : Validity.Invalid;
HeaderHashValidity = Utilities.SpansEqual(Layout.Hash, actualHeaderHash) ? Validity.Valid : Validity.Invalid;
SignatureValidity = ValidateSignature(keyset);
}
@ -95,7 +95,7 @@ namespace LibHac.FsSystem.Save
CryptoOld.CalculateAesCmac(keyset.SaveMacKey, Data, 0x100, calculatedCmac, 0, 0x200);
return Util.ArraysEqual(calculatedCmac, Cmac) ? Validity.Valid : Validity.Invalid;
return Utilities.ArraysEqual(calculatedCmac, Cmac) ? Validity.Valid : Validity.Invalid;
}
}

View File

@ -59,7 +59,7 @@ namespace LibHac.FsSystem.Save
position.NextFile = entry.NextSibling;
info = entry.Value;
name = Util.GetUtf8StringNullTerminated(nameBytes);
name = Utilities.GetUtf8StringNullTerminated(nameBytes);
return true;
}
@ -85,7 +85,7 @@ namespace LibHac.FsSystem.Save
position.NextDirectory = entry.NextSibling;
name = Util.GetUtf8StringNullTerminated(nameBytes);
name = Utilities.GetUtf8StringNullTerminated(nameBytes);
return true;
}

View File

@ -64,8 +64,8 @@ namespace LibHac.FsSystem.Save
int physicalBlockCount = virtualBlockCount + Header.JournalBlockCount;
int blockMapLength = virtualBlockCount * MapEntryLength;
int physicalBitmapLength = Util.AlignUp(physicalBlockCount, 32) / 8;
int virtualBitmapLength = Util.AlignUp(virtualBlockCount, 32) / 8;
int physicalBitmapLength = Utilities.AlignUp(physicalBlockCount, 32) / 8;
int virtualBitmapLength = Utilities.AlignUp(virtualBlockCount, 32) / 8;
MapStorage.Slice(blockMapLength).Fill(SaveDataFileSystem.TrimFillValue);
FreeBlocks.Slice(physicalBitmapLength).Fill(SaveDataFileSystem.TrimFillValue);

View File

@ -58,7 +58,7 @@ namespace LibHac.FsSystem.Save
return Result.Success;
}
int blockCount = (int)Util.DivideByRoundUp(size, AllocationTable.Header.BlockSize);
int blockCount = (int)Utilities.DivideByRoundUp(size, AllocationTable.Header.BlockSize);
int startBlock = AllocationTable.Allocate(blockCount);
if (startBlock == -1)

View File

@ -20,7 +20,7 @@ namespace LibHac.FsSystem
baseStorage.GetSize(out long baseSize).ThrowIfFailure();
SectorCount = (int)Util.DivideByRoundUp(baseSize, SectorSize);
SectorCount = (int)Utilities.DivideByRoundUp(baseSize, SectorSize);
Length = baseSize;
LeaveOpen = leaveOpen;
@ -57,7 +57,7 @@ namespace LibHac.FsSystem
rc = BaseStorage.GetSize(out long newSize);
if (rc.IsFailure()) return rc;
SectorCount = (int)Util.DivideByRoundUp(newSize, SectorSize);
SectorCount = (int)Utilities.DivideByRoundUp(newSize, SectorSize);
Length = newSize;
return Result.Success;

View File

@ -20,19 +20,19 @@ namespace LibHac
private const int SdCardKeyIdCount = 3;
public byte[][] KeyblobKeys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] KeyblobMacKeys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] EncryptedKeyblobs { get; } = Util.CreateJaggedByteArray(0x20, 0xB0);
public byte[][] Keyblobs { get; } = Util.CreateJaggedByteArray(0x20, 0x90);
public byte[][] KeyblobKeySources { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] KeyblobKeys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] KeyblobMacKeys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] EncryptedKeyblobs { get; } = Utilities.CreateJaggedByteArray(0x20, 0xB0);
public byte[][] Keyblobs { get; } = Utilities.CreateJaggedByteArray(0x20, 0x90);
public byte[][] KeyblobKeySources { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[] KeyblobMacKeySource { get; } = new byte[0x10];
public byte[][] TsecRootKeys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] MasterKekSources { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] MasterKeks { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] TsecRootKeys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] MasterKekSources { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] MasterKeks { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[] MasterKeySource { get; } = new byte[0x10];
public byte[][] MasterKeys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] Package1Keys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] Package2Keys { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][] MasterKeys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] Package1Keys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][] Package2Keys { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[] Package2KeySource { get; } = new byte[0x10];
public byte[] AesKekGenerationSource { get; } = new byte[0x10];
public byte[] AesKeyGenerationSource { get; } = new byte[0x10];
@ -46,29 +46,29 @@ namespace LibHac
public byte[] TitleKekSource { get; } = new byte[0x10];
public byte[] HeaderKekSource { get; } = new byte[0x10];
public byte[] SdCardKekSource { get; } = new byte[0x10];
public byte[][] SdCardKeySources { get; } = Util.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public byte[][] SdCardKeySources { get; } = Utilities.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public byte[] HeaderKeySource { get; } = new byte[0x20];
public byte[] HeaderKey { get; } = new byte[0x20];
public byte[] XciHeaderKey { get; } = new byte[0x10];
public byte[][] TitleKeks { get; } = Util.CreateJaggedByteArray(0x20, 0x10);
public byte[][][] KeyAreaKeys { get; } = Util.CreateJaggedByteArray(0x20, 3, 0x10);
public byte[][] TitleKeks { get; } = Utilities.CreateJaggedByteArray(0x20, 0x10);
public byte[][][] KeyAreaKeys { get; } = Utilities.CreateJaggedByteArray(0x20, 3, 0x10);
public byte[] EticketRsaKek { get; } = new byte[0x10];
public byte[] RetailSpecificAesKeySource { get; } = new byte[0x10];
public byte[] PerConsoleKeySource { get; } = new byte[0x10];
public byte[] BisKekSource { get; } = new byte[0x10];
public byte[][] BisKeySource { get; } = Util.CreateJaggedByteArray(4, 0x20);
public byte[][] BisKeySource { get; } = Utilities.CreateJaggedByteArray(4, 0x20);
public byte[] SslRsaKek { get; } = new byte[0x10];
// Device-specific keys
public byte[] SecureBootKey { get; } = new byte[0x10];
public byte[] TsecKey { get; } = new byte[0x10];
public byte[] DeviceKey { get; } = new byte[0x10];
public byte[][] BisKeys { get; } = Util.CreateJaggedByteArray(4, 0x20);
public byte[][] BisKeys { get; } = Utilities.CreateJaggedByteArray(4, 0x20);
public byte[] SaveMacKey { get; } = new byte[0x10];
public byte[] SaveMacSdCardKey { get; } = new byte[0x10];
public byte[] SdSeed { get; } = new byte[0x10];
public byte[][] SdCardKeySourcesSpecific { get; } = Util.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public byte[][] SdCardKeys { get; } = Util.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public byte[][] SdCardKeySourcesSpecific { get; } = Utilities.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public byte[][] SdCardKeys { get; } = Utilities.CreateJaggedByteArray(SdCardKeyIdCount, 0x20);
public RSAParameters EticketExtKeyRsa { get; set; }
@ -297,7 +297,7 @@ namespace LibHac
Array.Copy(EncryptedKeyblobs[i], expectedCmac, 0x10);
CryptoOld.CalculateAesCmac(KeyblobMacKeys[i], EncryptedKeyblobs[i], 0x10, cmac, 0, 0xa0);
if (!Util.ArraysEqual(cmac, expectedCmac))
if (!Utilities.ArraysEqual(cmac, expectedCmac))
{
logger?.LogMessage($"Warning: Keyblob MAC {i:x2} is invalid. Are SBK/TSEC key correct?");
}

View File

@ -67,7 +67,7 @@ namespace LibHac
// Increase the counter by one and start decrypting at 0x110.
var counter = new byte[0x10];
Array.Copy(Header.Counter, counter, 0x10);
Util.IncrementByteArray(counter);
Utilities.IncrementByteArray(counter);
return new CachedStorage(new Aes128CtrStorage(encStorage, Key, counter, true), 0x4000, 4, true);
}

View File

@ -87,7 +87,7 @@ namespace LibHac
public string GetRateString()
{
return Util.GetBytesReadable((long) (_timedBytes / _watch.Elapsed.TotalSeconds)) + "/s";
return Utilities.GetBytesReadable((long) (_timedBytes / _watch.Elapsed.TotalSeconds)) + "/s";
}
private void TimerHandler(object state)

View File

@ -111,7 +111,7 @@ namespace LibHac
throw new ArgumentOutOfRangeException();
}
long bodyStart = Util.GetNextMultiple(4 + sigLength, 0x40);
long bodyStart = Utilities.GetNextMultiple(4 + sigLength, 0x40);
writer.Write((int)SignatureType);

View File

@ -7,7 +7,7 @@ using System.Text;
namespace LibHac
{
public static class Util
public static class Utilities
{
private const int MediaSize = 0x200;
@ -189,7 +189,7 @@ namespace LibHac
return text;
}
public static string ReadUtf8Z(this BinaryReader reader, int maxLength = Int32.MaxValue)
public static string ReadUtf8Z(this BinaryReader reader, int maxLength = int.MaxValue)
{
long start = reader.BaseStream.Position;
int size = 0;

View File

@ -138,7 +138,7 @@ namespace LibHac
Span<byte> actualHeaderHash = stackalloc byte[Sha256.DigestSize];
Sha256.GenerateSha256Hash(headerBytes, actualHeaderHash);
PartitionFsHeaderValidity = Util.SpansEqual(RootPartitionHeaderHash, actualHeaderHash) ? Validity.Valid : Validity.Invalid;
PartitionFsHeaderValidity = Utilities.SpansEqual(RootPartitionHeaderHash, actualHeaderHash) ? Validity.Valid : Validity.Invalid;
}
}
}

View File

@ -43,7 +43,7 @@ namespace hactoolnet
src.GetSize(out long srcSize).ThrowIfFailure();
string rate = Util.GetBytesReadable((long)(srcSize * iterations / encryptWatch.Elapsed.TotalSeconds));
string rate = Utilities.GetBytesReadable((long)(srcSize * iterations / encryptWatch.Elapsed.TotalSeconds));
logger.LogMessage($"{label}{rate}/s");
}
@ -77,9 +77,9 @@ namespace hactoolnet
double averageRun = runTimes.Average();
double slowestRun = runTimes.Max();
string fastestRate = Util.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Util.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Util.GetBytesReadable((long)(srcSize / slowestRun));
string fastestRate = Utilities.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Utilities.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Utilities.GetBytesReadable((long)(srcSize / slowestRun));
logger.LogMessage($"{label}{averageRate}/s, fastest run: {fastestRate}/s, slowest run: {slowestRate}/s");
}
@ -122,9 +122,9 @@ namespace hactoolnet
double averageRun = runTimes.Average();
double slowestRun = runTimes.Max();
string fastestRate = Util.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Util.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Util.GetBytesReadable((long)(srcSize / slowestRun));
string fastestRate = Utilities.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Utilities.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Utilities.GetBytesReadable((long)(srcSize / slowestRun));
logger.LogMessage($"{label}{averageRate}/s, fastest run: {fastestRate}/s, slowest run: {slowestRate}/s");
}
@ -174,9 +174,9 @@ namespace hactoolnet
double averageRun = runTimes.Average();
double slowestRun = runTimes.Max();
string fastestRate = Util.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Util.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Util.GetBytesReadable((long)(srcSize / slowestRun));
string fastestRate = Utilities.GetBytesReadable((long)(srcSize / fastestRun));
string averageRate = Utilities.GetBytesReadable((long)(srcSize / averageRun));
string slowestRate = Utilities.GetBytesReadable((long)(srcSize / slowestRun));
logger.LogMessage($"{label}{averageRate}/s, fastest run: {fastestRate}/s, slowest run: {slowestRate}/s");
}
@ -379,7 +379,7 @@ namespace hactoolnet
cyclesPerByteString = $" ({cyclesPerByte:N3}x)";
}
return Util.GetBytesReadable((long)bytesPerSec) + "/s" + cyclesPerByteString;
return Utilities.GetBytesReadable((long)bytesPerSec) + "/s" + cyclesPerByteString;
}
public static void Process(Context ctx)

View File

@ -60,7 +60,7 @@ namespace hactoolnet
AesXtsFileHeader header = xtsFile.Header;
uint magic = header.Magic;
PrintItem(sb, colLen, " Magic:", Util.GetUtf8String(SpanHelpers.AsReadOnlyByteSpan(ref magic)));
PrintItem(sb, colLen, " Magic:", Utilities.GetUtf8String(SpanHelpers.AsReadOnlyByteSpan(ref magic)));
PrintItem(sb, colLen, " Content Type:", GetContentType(contentType));
PrintItem(sb, colLen, " Content Size:", $"{header.Size:x12}");
PrintItem(sb, colLen, " Header HMAC:", header.Signature);

View File

@ -247,7 +247,7 @@ namespace hactoolnet
PrintItem(sb, colLen, "SDK Version:", nca.Header.SdkVersion);
PrintItem(sb, colLen, "Distribution type:", nca.Header.DistributionType);
PrintItem(sb, colLen, "Content Type:", nca.Header.ContentType);
PrintItem(sb, colLen, "Master Key Revision:", $"{masterKey} ({Util.GetKeyRevisionSummary(masterKey)})");
PrintItem(sb, colLen, "Master Key Revision:", $"{masterKey} ({Utilities.GetKeyRevisionSummary(masterKey)})");
PrintItem(sb, colLen, "Encryption Type:", $"{(nca.Header.HasRightsId ? "Titlekey crypto" : "Standard crypto")}");
if (nca.Header.HasRightsId)

View File

@ -333,9 +333,9 @@ namespace hactoolnet
PrintItem(sb, colLen, "Save Type:", $"{save.Header.ExtraData.Type}");
PrintItem(sb, colLen, "Owner ID:", $"{save.Header.ExtraData.SaveOwnerId:x16}");
PrintItem(sb, colLen, "Timestamp:", $"{DateTimeOffset.FromUnixTimeSeconds(save.Header.ExtraData.Timestamp):yyyy-MM-dd HH:mm:ss} UTC");
PrintItem(sb, colLen, "Save Data Size:", $"0x{save.Header.ExtraData.DataSize:x16} ({Util.GetBytesReadable(save.Header.ExtraData.DataSize)})");
PrintItem(sb, colLen, "Journal Size:", $"0x{save.Header.ExtraData.JournalSize:x16} ({Util.GetBytesReadable(save.Header.ExtraData.JournalSize)})");
PrintItem(sb, colLen, "Free Space:", $"0x{freeSpace:x16} ({Util.GetBytesReadable(freeSpace)})");
PrintItem(sb, colLen, "Save Data Size:", $"0x{save.Header.ExtraData.DataSize:x16} ({Utilities.GetBytesReadable(save.Header.ExtraData.DataSize)})");
PrintItem(sb, colLen, "Journal Size:", $"0x{save.Header.ExtraData.JournalSize:x16} ({Utilities.GetBytesReadable(save.Header.ExtraData.JournalSize)})");
PrintItem(sb, colLen, "Free Space:", $"0x{freeSpace:x16} ({Utilities.GetBytesReadable(freeSpace)})");
PrintItem(sb, colLen, $"Header Hash{save.Header.HeaderHashValidity.GetValidityString()}:", save.Header.Layout.Hash);
PrintItem(sb, colLen, "Number of Files:", save.EnumerateEntries().Count(x => x.Type == DirectoryEntryType.File));

View File

@ -242,7 +242,7 @@ namespace hactoolnet
$"v{title.Version?.Version}",
title.Version?.ToString(),
title.Metadata?.Type.ToString(),
Util.GetBytesReadable(title.GetSize()),
Utilities.GetBytesReadable(title.GetSize()),
title.Control.Value.DisplayVersion.ToString(),
title.Name);
}
@ -272,17 +272,17 @@ namespace hactoolnet
if (app.Main != null)
{
sb.AppendLine($"Software: {Util.GetBytesReadable(app.Main.GetSize())}");
sb.AppendLine($"Software: {Utilities.GetBytesReadable(app.Main.GetSize())}");
}
if (app.Patch != null)
{
sb.AppendLine($"Update Data: {Util.GetBytesReadable(app.Patch.GetSize())}");
sb.AppendLine($"Update Data: {Utilities.GetBytesReadable(app.Patch.GetSize())}");
}
if (app.AddOnContent.Count > 0)
{
sb.AppendLine($"DLC: {Util.GetBytesReadable(app.AddOnContent.Sum(x => x.GetSize()))}");
sb.AppendLine($"DLC: {Utilities.GetBytesReadable(app.AddOnContent.Sum(x => x.GetSize()))}");
}
ref ApplicationControlProperty nacp = ref app.Nacp.Value;
@ -291,11 +291,11 @@ namespace hactoolnet
long deviceTotalSaveDataSize = nacp.DeviceSaveDataSize + nacp.DeviceSaveDataJournalSize;
if (userTotalSaveDataSize > 0)
sb.AppendLine($"User save: {Util.GetBytesReadable(userTotalSaveDataSize)}");
sb.AppendLine($"User save: {Utilities.GetBytesReadable(userTotalSaveDataSize)}");
if (deviceTotalSaveDataSize > 0)
sb.AppendLine($"System save: {Util.GetBytesReadable(deviceTotalSaveDataSize)}");
sb.AppendLine($"System save: {Utilities.GetBytesReadable(deviceTotalSaveDataSize)}");
if (nacp.BcatDeliveryCacheStorageSize > 0)
sb.AppendLine($"BCAT save: {Util.GetBytesReadable(nacp.BcatDeliveryCacheStorageSize)}");
sb.AppendLine($"BCAT save: {Utilities.GetBytesReadable(nacp.BcatDeliveryCacheStorageSize)}");
sb.AppendLine();
}

View File

@ -150,7 +150,7 @@ namespace hactoolnet
PrintItem(sb, colLen, $"Header Signature{xci.Header.SignatureValidity.GetValidityString()}:", xci.Header.Signature);
PrintItem(sb, colLen, $"Header Hash{xci.Header.PartitionFsHeaderValidity.GetValidityString()}:", xci.Header.RootPartitionHeaderHash);
PrintItem(sb, colLen, "Cartridge Type:", GetCartridgeType(xci.Header.GameCardSize));
PrintItem(sb, colLen, "Cartridge Size:", $"0x{Util.MediaToReal(xci.Header.ValidDataEndPage + 1):x12}");
PrintItem(sb, colLen, "Cartridge Size:", $"0x{Utilities.MediaToReal(xci.Header.ValidDataEndPage + 1):x12}");
PrintItem(sb, colLen, "Header IV:", xci.Header.AesCbcIv);
PrintPartition(sb, colLen, xci.OpenPartition(XciPartitionType.Root), XciPartitionType.Root);