Skip to content

Commit 439b49e

Browse files
innocenzibrendt
andauthored
feat(cryptography): introduce cryptography component (#1346)
Co-authored-by: Brent Roose <[email protected]>
1 parent 754a657 commit 439b49e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+1838
-5
lines changed

composer.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@
8282
"tempest/console": "self.version",
8383
"tempest/container": "self.version",
8484
"tempest/core": "self.version",
85+
"tempest/cryptography": "self.version",
8586
"tempest/database": "self.version",
8687
"tempest/datetime": "self.version",
8788
"tempest/debug": "self.version",
@@ -119,6 +120,7 @@
119120
"Tempest\\Console\\": "packages/console/src",
120121
"Tempest\\Container\\": "packages/container/src",
121122
"Tempest\\Core\\": "packages/core/src",
123+
"Tempest\\Cryptography\\": "packages/cryptography/src",
122124
"Tempest\\Database\\": "packages/database/src",
123125
"Tempest\\DateTime\\": "packages/datetime/src",
124126
"Tempest\\Debug\\": "packages/debug/src",
@@ -185,6 +187,7 @@
185187
"Tempest\\Console\\Tests\\": "packages/console/tests",
186188
"Tempest\\Container\\Tests\\": "packages/container/tests",
187189
"Tempest\\Core\\Tests\\": "packages/core/tests",
190+
"Tempest\\Cryptography\\Tests\\": "packages/cryptography/tests",
188191
"Tempest\\Database\\Tests\\": "packages/database/tests",
189192
"Tempest\\DateTime\\Tests\\": "packages/datetime/tests",
190193
"Tempest\\EventBus\\Tests\\": "packages/event-bus/tests",

packages/clock/src/GenericClock.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,9 @@ public function milliseconds(): int
4141

4242
public function sleep(int|Duration $milliseconds): void
4343
{
44-
if ($milliseconds instanceof Duration) {
45-
$milliseconds = (int) $milliseconds->getTotalMilliseconds();
46-
}
47-
48-
usleep($milliseconds * MILLISECONDS_PER_SECOND);
44+
usleep(match (true) {
45+
is_int($milliseconds) => $milliseconds * MILLISECONDS_PER_SECOND,
46+
$milliseconds instanceof Duration => (int) $milliseconds->getTotalMicroseconds(),
47+
});
4948
}
5049
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Exclude build/test files from the release
2+
.github/ export-ignore
3+
tests/ export-ignore
4+
.gitattributes export-ignore
5+
.gitignore export-ignore
6+
phpunit.xml export-ignore
7+
README.md export-ignore
8+
9+
# Configure diff output
10+
*.view.php diff=html
11+
*.php diff=php
12+
*.css diff=css
13+
*.html diff=html
14+
*.md diff=markdown

packages/cryptography/LICENSE.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2024 Brent Roose [email protected]
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "tempest/cryptography",
3+
"description": "A component for working with passwords, hashing, and cryptography.",
4+
"license": "MIT",
5+
"minimum-stability": "dev",
6+
"require": {
7+
"php": "^8.4",
8+
"tempest/container": "dev-main",
9+
"tempest/support": "dev-main",
10+
"tempest/clock": "dev-main"
11+
},
12+
"autoload": {
13+
"psr-4": {
14+
"Tempest\\Cryptography\\": "src"
15+
}
16+
},
17+
"autoload-dev": {
18+
"psr-4": {
19+
"Tempest\\Cryptography\\Tests\\": "tests"
20+
}
21+
}
22+
}

packages/cryptography/phpunit.xml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd"
5+
bootstrap="vendor/autoload.php"
6+
executionOrder="depends,defects"
7+
beStrictAboutOutputDuringTests="true"
8+
displayDetailsOnPhpunitDeprecations="true"
9+
failOnPhpunitDeprecation="false"
10+
failOnRisky="true"
11+
failOnWarning="true"
12+
>
13+
<testsuites>
14+
<testsuite name="Tempest cryptography">
15+
<directory>tests</directory>
16+
</testsuite>
17+
</testsuites>
18+
<source restrictNotices="true" restrictWarnings="true" ignoreIndirectDeprecations="true">
19+
<include>
20+
<directory>src</directory>
21+
</include>
22+
</source>
23+
</phpunit>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace Tempest\Cryptography;
4+
5+
use Tempest\Console\Console;
6+
use Tempest\Console\ConsoleCommand;
7+
use Tempest\Console\ExitCode;
8+
use Tempest\Cryptography\Encryption\EncryptionConfig;
9+
use Tempest\Cryptography\Encryption\EncryptionKey;
10+
use Tempest\Support\Filesystem;
11+
use Tempest\Support\Regex;
12+
use Tempest\Support\Str;
13+
14+
use function Tempest\root_path;
15+
16+
final readonly class CreateSigningKeyCommand
17+
{
18+
public function __construct(
19+
private EncryptionConfig $encryptionConfig,
20+
private Console $console,
21+
) {}
22+
23+
#[ConsoleCommand('key:generate', description: 'Generates the signing key required to sign and verify data.')]
24+
public function __invoke(): ExitCode
25+
{
26+
$key = EncryptionKey::generate($this->encryptionConfig->algorithm);
27+
28+
$this->console->writeln();
29+
$this->console->success('Signing key generated successfully.');
30+
31+
$this->createDotEnvIfNotExists();
32+
$this->addToDotEnv($key->toString());
33+
34+
return ExitCode::SUCCESS;
35+
}
36+
37+
private function getDotEnvPath(): string
38+
{
39+
return root_path('.env');
40+
}
41+
42+
private function addToDotEnv(string $key): void
43+
{
44+
$file = Filesystem\read_file($this->getDotEnvPath());
45+
46+
if (! Str\contains($file, 'SIGNING_KEY=')) {
47+
$file .= "\nSIGNING_KEY={$key}\n";
48+
} else {
49+
$file = Regex\replace($file, '/^SIGNING_KEY=.*$/m', "SIGNING_KEY={$key}");
50+
}
51+
52+
Filesystem\write_file($this->getDotEnvPath(), $file);
53+
}
54+
55+
private function createDotEnvIfNotExists(): void
56+
{
57+
if (Filesystem\exists($this->getDotEnvPath())) {
58+
return;
59+
}
60+
61+
Filesystem\create_file($this->getDotEnvPath());
62+
}
63+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
namespace Tempest\Cryptography\Encryption;
4+
5+
use Stringable;
6+
use Tempest\Cryptography\Encryption\Exceptions\EncryptedDataWasInvalid;
7+
use Tempest\Cryptography\Signing\Signature;
8+
use Tempest\Support\Json;
9+
10+
final readonly class EncryptedData implements Stringable
11+
{
12+
public function __construct(
13+
private(set) string $payload,
14+
private(set) string $iv,
15+
private(set) string $tag,
16+
private(set) Signature $signature,
17+
private(set) EncryptionAlgorithm $algorithm,
18+
) {}
19+
20+
public function serialize(): string
21+
{
22+
$data = [
23+
'payload' => base64_encode($this->payload),
24+
'iv' => base64_encode($this->iv),
25+
'tag' => base64_encode($this->tag),
26+
'signature' => $this->signature->value,
27+
'algorithm' => $this->algorithm->value,
28+
];
29+
30+
return base64_encode(Json\encode($data));
31+
}
32+
33+
public static function unserialize(string $data): self
34+
{
35+
$decoded = Json\decode(base64_decode($data, strict: true));
36+
37+
if (! is_array($decoded) || ! isset($decoded['payload'], $decoded['iv'], $decoded['tag'], $decoded['signature'], $decoded['algorithm'])) {
38+
throw EncryptedDataWasInvalid::dueToInvalidFormat();
39+
}
40+
41+
return new self(
42+
payload: base64_decode($decoded['payload'], strict: true),
43+
iv: base64_decode($decoded['iv'], strict: true),
44+
tag: base64_decode($decoded['tag'], strict: true),
45+
signature: new Signature($decoded['signature']),
46+
algorithm: EncryptionAlgorithm::from($decoded['algorithm']),
47+
);
48+
}
49+
50+
public function __toString(): string
51+
{
52+
return $this->serialize();
53+
}
54+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Tempest\Cryptography\Encryption;
4+
5+
interface Encrypter
6+
{
7+
public EncryptionAlgorithm $algorithm {
8+
get;
9+
}
10+
11+
/**
12+
* Encrypts the specified data.
13+
*/
14+
public function encrypt(#[\SensitiveParameter] string $data): EncryptedData;
15+
16+
/**
17+
* Decrypts the specified data.
18+
*/
19+
public function decrypt(string|EncryptedData $data): string;
20+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Tempest\Cryptography\Encryption;
4+
5+
use Tempest\Container\Container;
6+
use Tempest\Container\Initializer;
7+
use Tempest\Container\Singleton;
8+
use Tempest\Cryptography\Signing\Signer;
9+
10+
final class EncrypterInitializer implements Initializer
11+
{
12+
#[Singleton]
13+
public function initialize(Container $container): Encrypter
14+
{
15+
return new GenericEncrypter(
16+
signer: $container->get(Signer::class),
17+
config: $container->get(EncryptionConfig::class),
18+
);
19+
}
20+
}

0 commit comments

Comments
 (0)