25
In cryptography, PKCS#7 padding is a padding scheme which adds a number of bytes N ≥ 1, where the value of each added byte is equal to N.
For example, Hello, World!
, which has 13 bytes, is the following in hex:
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21
If we choose to PKCS#7 pad to length 16, then the result is:
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 03 03 03
And if we choose to pad to length 20, then the result is:
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 07 07 07 07 07 07
Note that in the first example we add three 03
bytes, and in the second we add seven 07
bytes.
Your task will be to validate whether a string (or integer array) has correct PKCS#7 padding. That is, if the last byte of the input string is N, then your program should check that the last N bytes of the string are equal to N.
Input
A single nonempty ASCII string containing characters between code points 1 and 127 inclusive. If you wish, you may take input as an array of integers instead.
Output
A truthy value if the input string has valid PKCS#7 padding, otherwise a falsy value.
Both functions and full programs are acceptable. This is code-golf, so the aim is to minimise the number of bytes in your code.
Test cases
The integer array version of inputs is presented here — the string version would have unprintable characters for many of the following test cases:
Truthy:
[1]
[1, 1]
[2, 1]
[2, 2]
[5, 6, 5, 3, 3, 3]
[1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2]
[95, 115, 80, 32, 71, 7, 122, 49, 13, 7, 7, 7, 7, 7, 7, 7, 7]
[27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
[15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15]
Falsy:
[2]
[1, 2]
[5, 5, 5, 5]
[5, 6, 5, 4, 4, 4]
[3, 3, 3, 94, 3, 3]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 127]
[50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7]
[26, 27, 59, 25, 122, 110, 20, 30, 114, 6, 9, 62, 121, 42, 22, 60, 33, 12]
Is
[1 2 3 3 3 3]
truthy or falsey? I think it should be truthy but I'm not positive. – James – 2016-08-27T16:54:54.320@DJMcMayhem Truthy – Jakube – 2016-08-27T16:58:39.280
@DJMcMayhem Truthy (this parallels the truthy test case ending in
7
s). You can think of it as, after stripping, you'd end up with[1 2 3]
. – Sp3000 – 2016-08-27T17:24:53.553Surely you meant to put a comma after Hello. (It's in the hex.) – rici – 2016-08-28T03:43:48.230
@rici Thanks for noticing, fixed! – Sp3000 – 2016-08-28T03:50:36.567
Can I also take the index of the last element of the array as input? Or a pointer to the last element instead of the first (in C)? – Riley – 2016-08-29T15:07:35.767
@Riley Taking a pointer to/index of the last element feels a bit like preprocessing to me, so no. My intention with C was that since 0 will not be in the input, you can assume the array is null terminated. – Sp3000 – 2016-08-29T21:34:49.480