summary refs log tree commit diff
path: root/Crypto/src/crypto/paddings/TbcPadding.cs
blob: 74b64e8e1b01dd4b51eb46a369133e3b9360c881 (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
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Crypto.Paddings
{

    /// <summary> A padder that adds Trailing-Bit-Compliment padding to a block.
    /// <p>
    /// This padding pads the block out compliment of the last bit
    /// of the plain text.
    /// </p>
    /// </summary>
    public class TbcPadding
		: IBlockCipherPadding
    {
        /// <summary> Return the name of the algorithm the cipher implements.</summary>
        /// <returns> the name of the algorithm the cipher implements.
        /// </returns>
        public string PaddingName
        {
            get { return "TBC"; }
        }

		/// <summary> Initialise the padder.</summary>
        /// <param name="random">- a SecureRandom if available.
        /// </param>
        public virtual void Init(SecureRandom random)
        {
            // nothing to do.
        }

        /// <summary> add the pad bytes to the passed in block, returning the
        /// number of bytes added.
        /// <p>
        /// Note: this assumes that the last block of plain text is always
        /// passed to it inside in. i.e. if inOff is zero, indicating the
        /// entire block is to be overwritten with padding the value of in
        /// should be the same as the last block of plain text.
        /// </p>
        /// </summary>
        public virtual int AddPadding(byte[] input, int inOff)
        {
            int count = input.Length - inOff;
            byte code;

            if (inOff > 0)
            {
                code = (byte)((input[inOff - 1] & 0x01) == 0?0xff:0x00);
            }
            else
            {
                code = (byte)((input[input.Length - 1] & 0x01) == 0?0xff:0x00);
            }

            while (inOff < input.Length)
            {
                input[inOff] = code;
                inOff++;
            }

            return count;
        }

        /// <summary> return the number of pad bytes present in the block.</summary>
        public virtual int PadCount(byte[] input)
        {
            byte code = input[input.Length - 1];

            int index = input.Length - 1;
            while (index > 0 && input[index - 1] == code)
            {
                index--;
            }

            return input.Length - index;
        }
    }
}