EncryptedSubjectIdentifier::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\OpenIdConnect\UserInfo\Pairwise;
15
16
use Base64Url\Base64Url;
17
use OAuth2Framework\Component\Core\UserAccount\UserAccount;
18
19
final class EncryptedSubjectIdentifier implements PairwiseSubjectIdentifierAlgorithm
20
{
21
    /**
22
     * @var string
23
     */
24
    private $pairwiseEncryptionKey;
25
26
    /**
27
     * @var string
28
     */
29
    private $algorithm;
30
31
    /**
32
     * EncryptedSubjectIdentifier constructor.
33
     */
34
    public function __construct(string $pairwiseEncryptionKey, string $algorithm)
35
    {
36
        if (!\in_array($algorithm, openssl_get_cipher_methods(), true)) {
37
            throw new \InvalidArgumentException(\Safe\sprintf('The algorithm "%s" is not supported.', $algorithm));
38
        }
39
        $this->pairwiseEncryptionKey = $pairwiseEncryptionKey;
40
        $this->algorithm = $algorithm;
41
    }
42
43
    public function calculateSubjectIdentifier(UserAccount $userAccount, string $sectorIdentifierHost): string
44
    {
45
        $prepared = \Safe\sprintf('%s:%s', $sectorIdentifierHost, $userAccount->getUserAccountId()->getValue());
46
        $iv = hash('sha512', $userAccount->getUserAccountId()->getValue(), true);
47
        $ivSize = \Safe\openssl_cipher_iv_length($this->algorithm);
48
        $iv = mb_substr($iv, 0, $ivSize, '8bit');
49
50
        return Base64Url::encode($iv).':'.Base64Url::encode(\Safe\openssl_encrypt($prepared, $this->algorithm, $this->pairwiseEncryptionKey, OPENSSL_RAW_DATA, $iv));
51
    }
52
53
    public function getPublicIdFromSubjectIdentifier(string $subjectIdentifier): ?string
54
    {
55
        $data = explode(':', $subjectIdentifier);
56
        if (2 !== \count($data)) {
57
            return null;
58
        }
59
        $decoded = \Safe\openssl_decrypt(Base64Url::decode($data[1]), $this->algorithm, $this->pairwiseEncryptionKey, OPENSSL_RAW_DATA, Base64Url::decode($data[0]));
60
        $parts = explode(':', $decoded);
61
        if (3 !== \count($parts)) {
62
            return null;
63
        }
64
65
        return $parts[1];
66
    }
67
}
68