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
80
81
82
83
84
85
86
|
/*
* This file is part of cert-signer
* Copyright (c) 2024 Paolo Lulli.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.lulli.certsigner.ca;
import net.lulli.certsigner.util.FileCAUtils;
import net.lulli.certsigner.util.Serde;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
public class CaServer {
private static final String CA_PATH = System.getenv("HOME") + "/.config/tlscerts/CA";
private static final String CERTIFICATES_PATH = System.getenv("HOME") + "/.config/tlscerts";
private final String serviceName;
public CaServer(String serviceName) {
Objects.requireNonNull(serviceName);
this.serviceName = serviceName;
init();
}
private String getServiceCaDir() {
return CA_PATH + "/" + this.serviceName;
}
private String getClientCertsDir(String clientName) {
return CERTIFICATES_PATH + "/" + this.serviceName + "/" + clientName;
}
private String getCSRPath(String clientName) {
return CERTIFICATES_PATH + "/" + this.serviceName + "/" + clientName + "/" + clientName + ".csr";
}
private void init() {
var home = new File(getServiceCaDir());
if (!home.exists()) {
home.mkdirs();
}
}
public String getCsr(String clientName) {
try {
var caServer = new CaServer(this.serviceName);
return Files.readString(Paths.get(getCSRPath(clientName)));
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
}
public void initializeCa(String rootSubject, String rootKeyStorePass) {
FileCAUtils.initializeCa(rootSubject, getServiceCaDir(), rootKeyStorePass);
}
public String createCert(String rootKeyStorePass, String rootSubject, String clientName) {
var csrContent = getCsr(clientName);
var pkcs10CertificationRequest = Serde.pemToCsr(csrContent);
return FileCAUtils.signCertificateWithRootKeystore(getServiceCaDir() + "/root-cert.p12",
rootKeyStorePass,
pkcs10CertificationRequest,
rootSubject,
getClientCertsDir(clientName),
clientName
);
}
}
|