forked from dusnm/journal_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_gen
executable file
·72 lines (60 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
#!/bin/env php
<?php
define('KEYS_DIRECTORY', __DIR__.'/keys');
define('PRIVATE_KEY_PATH', __DIR__.'/keys/private.pem');
define('PUBLIC_KEY_PATH', __DIR__.'/keys/public.pem');
define('SECRET_KEY_PATH', __DIR__.'/keys/secret_key');
define('SECRET_KEY_NONCE_PATH', __DIR__.'/keys/secret_key_nonce');
define('PUBLIC_KEY_CRYPTO_DIGEST_ALGORITHM', 'sha512');
define('PUBLIC_KEY_CRYPTO_KEY_LENGTH', 4096);
/**
* Generates a public key cryptography key pair in string representation with the provided options.
*/
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'],
];
}
/**
* Generates pseudorandom bytes to be used as part of a symetric encryption/decrytpion key.
*/
function generate_secret_key_and_nonce(): array
{
return [
random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES),
random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
];
}
if (!file_exists(KEYS_DIRECTORY)) {
mkdir(KEYS_DIRECTORY, 0755);
}
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,
]);
file_put_contents(PUBLIC_KEY_PATH, $public_key);
file_put_contents(PRIVATE_KEY_PATH, $private_key);
// The private key must only be accessible by the owner
chmod(PRIVATE_KEY_PATH, 0600);
}
if (!file_exists(SECRET_KEY_PATH) && !file_exists(SECRET_KEY_NONCE_PATH)) {
[$secret_key, $secret_key_nonce] = generate_secret_key_and_nonce();
file_put_contents(SECRET_KEY_PATH, $secret_key);
file_put_contents(SECRET_KEY_NONCE_PATH, $secret_key_nonce);
}