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

Pkcs7Padding

A padder that adds PKCS7/PKCS5 padding to a block.
using Org.BouncyCastle.Security; using System; namespace Org.BouncyCastle.Crypto.Paddings { public class Pkcs7Padding : IBlockCipherPadding { public string PaddingName => "PKCS7"; public void Init(SecureRandom random) { } public int AddPadding(byte[] input, int inOff) { int num = input.Length - inOff; byte b = (byte)num; while (inOff < input.Length) { input[inOff++] = b; } return num; } public int AddPadding(Span<byte> block, int position) { int num = block.Length - position; byte value = (byte)num; block.Slice(position, block.Length - position).Fill(value); return num; } public int PadCount(byte[] input) { byte b = input[input.Length - 1]; int num = b; int num2 = input.Length - num; int num3 = (num2 | (num - 1)) >> 31; for (int i = 0; i < input.Length; i++) { num3 |= ((input[i] ^ b) & ~(i - num2 >> 31)); } if (num3 != 0) throw new InvalidCipherTextException("pad block corrupted"); return num; } public int PadCount(ReadOnlySpan<byte> block) { byte b = block[block.Length - 1]; int num = b; int num2 = block.Length - num; int num3 = (num2 | (num - 1)) >> 31; for (int i = 0; i < block.Length; i++) { num3 |= ((block[i] ^ b) & ~(i - num2 >> 31)); } if (num3 != 0) throw new InvalidCipherTextException("pad block corrupted"); return num; } } }