summary refs log tree commit diff
path: root/crypto/src/crypto/paddings/ISO10126d2Padding.cs
blob: 21e007f1bab21097a9d0b3f6858a13b23f9bf929 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;

using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Crypto.Paddings
{

    /**
    * A padder that adds ISO10126-2 padding to a block.
    */
    public class ISO10126d2Padding: IBlockCipherPadding
    {
        private SecureRandom random;

        /**
        * Initialise the padder.
        *
        * @param random a SecureRandom if available.
        */
        public void Init(
			SecureRandom random)
            //throws ArgumentException
        {
            this.random = CryptoServicesRegistrar.GetSecureRandom(random);
        }

		/**
        * Return the name of the algorithm the cipher implements.
        *
        * @return the name of the algorithm the cipher implements.
        */
        public string PaddingName
        {
            get { return "ISO10126-2"; }
        }

        public int AddPadding(byte[] input, int inOff)
        {
            int count = input.Length - inOff;
            if (count > 1)
            {
                random.NextBytes(input, inOff, count - 1);
            }
            input[input.Length - 1] = (byte)count;

            return count;
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public int AddPadding(Span<byte> block, int position)
        {
            int count = block.Length - position;
            if (count > 1)
            {
                random.NextBytes(block[position..(block.Length - 1)]);
            }
            block[block.Length - 1] = (byte)count;

            return count;
        }
#endif

        public int PadCount(byte[] input)
        {
            int count = input[input.Length -1];
            int position = input.Length - count;

            int failed = (position | (count - 1)) >> 31;
            if (failed != 0)
                throw new InvalidCipherTextException("pad block corrupted");

            return count;
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public int PadCount(ReadOnlySpan<byte> block)
        {
            int count = block[block.Length - 1];
            int position = block.Length - count;

            int failed = (position | (count - 1)) >> 31;
            if (failed != 0)
                throw new InvalidCipherTextException("pad block corrupted");

            return count;
        }
#endif
    }
}