<PackageReference Include="BouncyCastle.Cryptography" Version="2.6.1" />

X923Padding

A padder that adds X9.23 padding to a block - if a SecureRandom is passed in random padding is assumed, otherwise padding with zeros is used.
using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using System; namespace Org.BouncyCastle.Crypto.Paddings { public class X923Padding : IBlockCipherPadding { private SecureRandom m_random; public string PaddingName => "X9.23"; public void Init(SecureRandom random) { m_random = random; } public int AddPadding(byte[] input, int inOff) { int num = input.Length - inOff; if (num > 1) { if (m_random == null) Arrays.Fill(input, inOff, input.Length - 1, 0); else m_random.NextBytes(input, inOff, num - 1); } input[input.Length - 1] = (byte)num; return num; } public int AddPadding(Span<byte> block, int position) { int num = block.Length - position; if (num > 1) { Span<byte> buffer = block.Slice(position, block.Length - 1 - position); if (m_random == null) buffer.Fill(0); else m_random.NextBytes(buffer); } block[block.Length - 1] = (byte)num; return num; } public int PadCount(byte[] input) { int num = input[input.Length - 1]; if (((input.Length - num) | (num - 1)) >> 31 != 0) throw new InvalidCipherTextException("pad block corrupted"); return num; } public int PadCount(ReadOnlySpan<byte> block) { int num = block[block.Length - 1]; if (((block.Length - num) | (num - 1)) >> 31 != 0) throw new InvalidCipherTextException("pad block corrupted"); return num; } } }