-
Notifications
You must be signed in to change notification settings - Fork 1
/
key_gen
executable file
·79 lines (70 loc) · 2.21 KB
/
key_gen
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
#!/bin/env php
<?php
/**
* Generate cryptographic keys used in the application.
*
* @author Dusan Mitrovic <[email protected]>
* @licence https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
*/
define('KEYS_DIRECTORY', __DIR__.'/keys');
define('PRIVATE_KEY_PATH', __DIR__.'/keys/private.pem');
define('PUBLIC_KEY_PATH', __DIR__.'/keys/public.pem');
define('PUBLIC_KEY_CRYPTO_DIGEST_ALGORITHM', 'sha512');
define('PUBLIC_KEY_CRYPTO_KEY_LENGTH', 4096);
define('WRITE_ERROR', 'Unable to write to the disk, check permissions.');
/**
* Generates a public key cryptography key pair in string representation with the provided options.
*
* @return array public/private keypair
*/
function generate_public_key_crypto_key_pair(array $options): array
{
$key_pair = openssl_pkey_new($options);
$key_pair_details = openssl_pkey_get_details($key_pair);
openssl_pkey_export($key_pair, $private_key);
return [
$private_key,
$key_pair_details['key'],
];
}
/**
* Write the file to the disk
*
* @param string $path
* @param mixed $data
*
* @throws \Exception
*/
function write_to_file(string $path, $data): void
{
if (file_put_contents($path, $data) === false) {
throw new Error(WRITE_ERROR);
}
}
if (!file_exists(KEYS_DIRECTORY)) {
if (!mkdir(KEYS_DIRECTORY, 0755)) {
throw new Error(WRITE_ERROR);
}
}
if (!file_exists(PRIVATE_KEY_PATH) && !file_exists(PUBLIC_KEY_PATH)) {
/*
* Getting the string representation of private and public keys to be stored in a file
*
* Supported public key cryptography algorithms include:
* OPENSSL_KEYTYPE_RSA,
* OPENSSL_KEYTYPE_DSA,
* OPENSSL_KEYTYPE_DH,
* OPENSSL_KEYTYPE_EC
*/
[$private_key, $public_key] = generate_public_key_crypto_key_pair([
'digest_alg' => PUBLIC_KEY_CRYPTO_DIGEST_ALGORITHM,
'private_key_bits' => PUBLIC_KEY_CRYPTO_KEY_LENGTH,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);
write_to_file(PUBLIC_KEY_PATH, $public_key);
write_to_file(PRIVATE_KEY_PATH, $private_key);
// The private key must only be accessible by the owner
if (!chmod(PRIVATE_KEY_PATH, 0600)) {
throw new Error(WRITE_ERROR);
}
}