2using System.Security.Cryptography;
3using Org.BouncyCastle.Crypto;
4using Org.BouncyCastle.Crypto.Engines;
5using Org.BouncyCastle.Crypto.Modes;
6using Org.BouncyCastle.Crypto.Parameters;
15internal sealed class BouncyCastleAes : Aes
17 private const int BlockSizeInBytes = 16;
19 private static readonly
bool NativeSupported = IsNativeSupported();
24 internal static bool ForceBouncyCastle {
get;
set; }
29 internal static Aes CreateAes() =>
30 NativeSupported && !ForceBouncyCastle ? Aes.Create() :
new BouncyCastleAes();
33 private static bool IsNativeSupported()
37 using var aes = Aes.Create();
38 using var transform = aes.CreateEncryptor(
new byte[BlockSizeInBytes],
new byte[BlockSizeInBytes]);
41 catch (Exception exception) when (exception is PlatformNotSupportedException or CryptographicException)
51 public override ICryptoTransform CreateEncryptor(
byte[] rgbKey,
byte[] rgbIV) =>
52 CreateTransform(
true, rgbKey, rgbIV);
55 public override ICryptoTransform CreateDecryptor(
byte[] rgbKey,
byte[] rgbIV) =>
56 CreateTransform(
false, rgbKey, rgbIV);
61 public override void GenerateKey() => KeyValue = RandomBytes(KeySizeValue / 8);
64 public override void GenerateIV() => IVValue = RandomBytes(BlockSizeInBytes);
66 private static byte[] RandomBytes(
int count)
68 var bytes =
new byte[count];
69 using var random = RandomNumberGenerator.Create();
70 random.GetBytes(bytes);
74 private ICryptoTransform CreateTransform(
bool encrypt,
byte[] key,
byte[] iv)
76 if (Padding != PaddingMode.None && Padding != PaddingMode.Zeros)
78 throw new NotSupportedException($
"Padding mode {Padding} is not supported");
82 ICipherParameters parameters =
new KeyParameter(key);
86 cipher =
new AesEngine();
89 cipher =
new CbcBlockCipher(
new AesEngine());
90 parameters =
new ParametersWithIV(parameters, iv ??
new byte[BlockSizeInBytes]);
93 throw new NotSupportedException($
"Cipher mode {Mode} is not supported");
96 cipher.Init(encrypt, parameters);
97 return new BlockTransform(cipher);
104 private sealed class BlockTransform(IBlockCipher cipher) : ICryptoTransform
106 public int InputBlockSize => BlockSizeInBytes;
108 public int OutputBlockSize => BlockSizeInBytes;
110 public bool CanTransformMultipleBlocks =>
true;
112 public bool CanReuseTransform =>
false;
114 public int TransformBlock(
byte[] inputBuffer,
int inputOffset,
int inputCount,
byte[] outputBuffer,
117 if (inputCount % BlockSizeInBytes != 0)
119 throw new CryptographicException(
"The input must be a whole number of blocks");
122 for (var offset = 0; offset < inputCount; offset += BlockSizeInBytes)
124 cipher.ProcessBlock(inputBuffer, inputOffset + offset, outputBuffer, outputOffset + offset);
130 public byte[] TransformFinalBlock(
byte[] inputBuffer,
int inputOffset,
int inputCount)
132 var output =
new byte[inputCount];
133 TransformBlock(inputBuffer, inputOffset, inputCount, output, 0);
137 public void Dispose()