File: HexTest.php

package info (click to toggle)
php-constant-time 3.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 296 kB
  • sloc: php: 2,109; xml: 35; makefile: 16
file content (83 lines) | stat: -rw-r--r-- 2,080 bytes parent folder | download
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
<?php
namespace ParagonIE\ConstantTime\Tests;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ParagonIE\ConstantTime\Hex;
use function bin2hex;
use function strtoupper;

class HexTest extends TestCase
{
    public function testRandom(): void
    {
        for ($i = 1; $i < 32; ++$i) {
            for ($j = 0; $j < 50; ++$j) {
                $random = \random_bytes($i);

                $enc = Hex::encode($random);
                $this->assertSame(
                    $random,
                    Hex::decode($enc)
                );
                $this->assertSame(
                    bin2hex($random),
                    $enc
                );

                $enc = Hex::encodeUpper($random);
                $this->assertSame(
                    $random,
                    Hex::decode($enc)
                );
                $this->assertSame(
                    strtoupper(bin2hex($random)),
                    $enc
                );
            }
        }
    }

    public static function invalidCharactersProvider(): array
    {
        return [
            ['gg'],
            ['GG'],
            ['zz'],
            ['ZZ'],
            ['  '],
            ['ab de'],
        ];
    }

    /**
     * @dataProvider invalidCharactersProvider
     */
    #[DataProvider("invalidCharactersProvider")]
    public function testInvalidCharacters(string $encoded)
    {
        $this->expectException(\RangeException::class);
        Hex::decode($encoded);
    }

    public function testStrictPaddingSuccess(): void
    {
        Hex::decode('0a', true);
        $this->assertTrue(true); // To avoid risky test warning
    }

    public function testStrictPaddingFailure(): void
    {
        $this->expectException(\RangeException::class);
        Hex::decode('a', true);
    }

    public function testNonStrictPadding(): void
    {
        // Odd-length string with non-strict padding should be prepended with 0
        $this->assertSame(
            Hex::decode('0a'),
            Hex::decode('a')
        );
    }
}