1<?php
2
3/**
4 * This file is part of the FreeDSx SASL package.
5 *
6 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace FreeDSx\Sasl\Factory;
13
14use Exception;
15use FreeDSx\Sasl\Exception\SaslException;
16
17/**
18 * Used to generate a nonce value.
19 *
20 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
21 */
22trait NonceTrait
23{
24    /**
25     * From DIGEST-MD5:
26     *
27     * The cnonce-value is an opaque quoted string value provided by the client and used by both client and server to
28     * avoid chosen plaintext attacks, and to provide mutual authentication. The security of the implementation depends
29     * on a good choice. It is RECOMMENDED that it contain at least 64 bits of entropy.
30     *
31     * @throws SaslException
32     */
33    protected function generateNonce(int $byteLength): string
34    {
35        try {
36            return base64_encode(random_bytes($byteLength));
37        } catch (Exception $e) {
38            throw new SaslException(sprintf(
39                'Unable to generate the nonce: %s',
40                $e->getMessage()
41            ), $e->getCode(), $e);
42        }
43    }
44}