Improve AES-CTR performance

This commit is contained in:
Alex Barney 2018-06-29 18:49:53 -05:00
parent 16405583ce
commit d24028f34d
3 changed files with 32 additions and 87 deletions

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using libhac; using libhac;
@ -35,12 +36,17 @@ namespace hactoolnet
var title = sdfs.Titles[0x0100E95004038000]; var title = sdfs.Titles[0x0100E95004038000];
var nca = title.ProgramNca; var nca = title.ProgramNca;
var romfsStream = nca.OpenSection(1, false); var romfsStream = nca.OpenSection(1, false);
var romfs = new Romfs(romfsStream);
var file = romfs.OpenFile("/stream/voice/us/127/127390101.nop");
using (var output = new FileStream("127390101.nop", FileMode.Create)) var romfs = new Romfs(romfsStream);
var file = romfs.OpenFile("/bf2.ard");
using (var progress = new ProgressBar())
using (var output = new FileStream("bf2.ard", FileMode.Create))
{ {
file.CopyTo(output); var watch = Stopwatch.StartNew();
file.CopyStream(output, file.Length / 100, progress);
watch.Stop();
progress.LogMessage(watch.Elapsed.TotalSeconds.ToString());
} }
} }
@ -53,11 +59,15 @@ namespace hactoolnet
var romfsStream = nca.OpenSection(1, false); var romfsStream = nca.OpenSection(1, false);
var romfs = new Romfs(romfsStream); var romfs = new Romfs(romfsStream);
var bfstm = romfs.OpenFile("/Sound/Resource/Stream/BGM_Castle.bfstm"); var bfstm = romfs.OpenFile("/Sound/Resource/Stream/Demo149_1_SoundTrack.bfstm");
using (var output = new FileStream("BGM_Castle.bfstm", FileMode.Create)) using (var progress = new ProgressBar())
using (var output = new FileStream("Demo149_1_SoundTrack.bfstm", FileMode.Create))
{ {
bfstm.CopyTo(output); var watch = Stopwatch.StartNew();
bfstm.CopyStream(output, bfstm.Length, progress);
watch.Stop();
progress.LogMessage(watch.Elapsed.TotalSeconds.ToString());
} }
} }
} }

View file

@ -21,87 +21,39 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
namespace libhac namespace libhac
{ {
public class Aes128CounterMode : SymmetricAlgorithm public class CounterModeCryptoTransform
{
private readonly byte[] _counter = new byte[0x10];
private readonly AesManaged _aes;
public Aes128CounterMode()
{
_aes = new AesManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
};
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _counter);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _counter);
}
public override void GenerateKey()
{
_aes.GenerateKey();
}
public override void GenerateIV()
{
// IV not needed in Counter Mode
}
}
public class CounterModeCryptoTransform : ICryptoTransform
{ {
private const int BlockSize = 128;
private const int BlockSizeBytes = BlockSize / 8;
private readonly byte[] _counter; private readonly byte[] _counter;
private readonly byte[] _counterEnc = new byte[0x10];
private readonly ICryptoTransform _counterEncryptor; private readonly ICryptoTransform _counterEncryptor;
private readonly Queue<byte> _xorMask = new Queue<byte>();
private readonly SymmetricAlgorithm _symmetricAlgorithm;
public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] counter) public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] counter)
{ {
if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (key == null) throw new ArgumentNullException(nameof(key)); if (key == null) throw new ArgumentNullException(nameof(key));
if (counter == null) throw new ArgumentNullException(nameof(counter)); if (counter == null) throw new ArgumentNullException(nameof(counter));
if (counter.Length != symmetricAlgorithm.BlockSize / 8) if (counter.Length != BlockSizeBytes)
throw new ArgumentException(String.Format("Counter size must be same as block size (actual: {0}, expected: {1})", throw new ArgumentException(String.Format("Counter size must be same as block size (actual: {0}, expected: {1})",
counter.Length, symmetricAlgorithm.BlockSize / 8)); counter.Length, BlockSizeBytes));
_symmetricAlgorithm = symmetricAlgorithm;
_counter = counter; _counter = counter;
_counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, new byte[BlockSize / 8]);
var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv);
} }
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) public int TransformBlock(byte[] inputBuffer, int inputOffset, byte[] outputBuffer, int outputOffset)
{ {
var output = new byte[inputCount]; EncryptCounterThenIncrement();
TransformBlock(inputBuffer, inputOffset, inputCount, output, 0); for (int i = 0; i < 16; i++)
return output; {
outputBuffer[outputOffset + i] = (byte)(inputBuffer[inputOffset + i] ^ _counterEnc[i]);
} }
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) return 16;
{
for (var i = 0; i < inputCount; i++)
{
if (NeedMoreXorMaskBytes()) EncryptCounterThenIncrement();
var mask = _xorMask.Dequeue();
outputBuffer[outputOffset + i] = (byte)(inputBuffer[inputOffset + i] ^ mask);
}
return inputCount;
} }
public void UpdateCounter(long offset) public void UpdateCounter(long offset)
@ -114,22 +66,10 @@ namespace libhac
} }
} }
private bool NeedMoreXorMaskBytes()
{
return _xorMask.Count == 0;
}
private void EncryptCounterThenIncrement() private void EncryptCounterThenIncrement()
{ {
var counterModeBlock = new byte[_symmetricAlgorithm.BlockSize / 8]; _counterEncryptor.TransformBlock(_counter, 0, _counter.Length, _counterEnc, 0);
_counterEncryptor.TransformBlock(_counter, 0, _counter.Length, counterModeBlock, 0);
IncrementCounter(); IncrementCounter();
foreach (var b in counterModeBlock)
{
_xorMask.Enqueue(b);
}
} }
private void IncrementCounter() private void IncrementCounter()
@ -141,11 +81,6 @@ namespace libhac
} }
} }
public int InputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public int OutputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public bool CanTransformMultipleBlocks => true;
public bool CanReuseTransform => false;
public void Dispose() public void Dispose()
{ {
} }

View file

@ -166,7 +166,7 @@ namespace libhac
_decryptor = CreateDecryptor(); _decryptor = CreateDecryptor();
//decrypt the sector //decrypt the sector
var retV = _decryptor.TransformBlock(_tempBuffer, 0, ret, buffer, offset); var retV = _decryptor.TransformBlock(_tempBuffer, 0, buffer, offset);
//Console.WriteLine("Decrypting sector {0} == {1} bytes", currentSector, retV); //Console.WriteLine("Decrypting sector {0} == {1} bytes", currentSector, retV);