Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/CryptoBridge/Crypto.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\CryptoBridge;
6
7 use function defined;
8 use RuntimeException;
9 use SpomkyLabs\Pki\CryptoBridge\Crypto\OpenSSLCrypto;
10 use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Cipher\CipherAlgorithmIdentifier;
11 use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
12 use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo;
13 use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
14 use SpomkyLabs\Pki\CryptoTypes\Signature\Signature;
15
16 /**
17 * Base class for crypto engine implementations.
18 */
19 abstract class Crypto
20 {
21 /**
22 * Sign data with given algorithm using given private key.
23 *
24 * @param string $data Data to sign
25 * @param PrivateKeyInfo $privkey_info Private key
26 * @param SignatureAlgorithmIdentifier $algo Signature algorithm
27 */
28 abstract public function sign(
29 string $data,
30 PrivateKeyInfo $privkey_info,
31 SignatureAlgorithmIdentifier $algo
32 ): Signature;
33
34 /**
35 * Verify signature with given algorithm using given public key.
36 *
37 * @param string $data Data to verify
38 * @param Signature $signature Signature
39 * @param PublicKeyInfo $pubkey_info Public key
40 * @param SignatureAlgorithmIdentifier $algo Signature algorithm
41 *
42 * @return bool True if signature matches
43 */
44 abstract public function verify(
45 string $data,
46 Signature $signature,
47 PublicKeyInfo $pubkey_info,
48 SignatureAlgorithmIdentifier $algo
49 ): bool;
50
51 /**
52 * Encrypt data with given algorithm using given key.
53 *
54 * Padding must be added by the caller. Initialization vector is taken from the algorithm identifier if available.
55 *
56 * @param string $data Plaintext
57 * @param string $key Encryption key
58 * @param CipherAlgorithmIdentifier $algo Encryption algorithm
59 *
60 * @return string Ciphertext
61 */
62 abstract public function encrypt(string $data, string $key, CipherAlgorithmIdentifier $algo): string;
63
64 /**
65 * Decrypt data with given algorithm using given key.
66 *
67 * Possible padding is not removed and must be handled by the caller. Initialization vector is taken from the
68 * algorithm identifier if available.
69 *
70 * @param string $data Ciphertext
71 * @param string $key Encryption key
72 * @param CipherAlgorithmIdentifier $algo Encryption algorithm
73 *
74 * @return string Plaintext
75 */
76 abstract public function decrypt(string $data, string $key, CipherAlgorithmIdentifier $algo): string;
77
78 /**
79 * Get default supported crypto implementation.
80 */
81 public static function getDefault(): self
82 {
83 if (defined('OPENSSL_VERSION_NUMBER')) {
84 return new OpenSSLCrypto();
85 }
86 // @codeCoverageIgnoreStart
87 throw new RuntimeException('No crypto implementation available.');
88 // @codeCoverageIgnoreEnd
89 }
90 }