提交 | 用户 | 时间
|
a6de49
|
1 |
package com.iailab.module.data.channel.opcua.collector; |
H |
2 |
|
|
3 |
import org.slf4j.Logger; |
|
4 |
import org.slf4j.LoggerFactory; |
|
5 |
|
|
6 |
import java.io.InputStream; |
|
7 |
import java.nio.file.Files; |
|
8 |
import java.nio.file.Path; |
|
9 |
import java.security.*; |
|
10 |
import java.security.cert.X509Certificate; |
|
11 |
import java.util.regex.Pattern; |
|
12 |
|
|
13 |
/** |
|
14 |
* @author PanZhibao |
|
15 |
* @Description |
|
16 |
* @createTime 2022年07月22日 14:44:00 |
|
17 |
*/ |
|
18 |
public class KeyStoreLoader { |
|
19 |
|
|
20 |
private static final Pattern IP_ADDR_PATTERN = Pattern.compile( |
|
21 |
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); |
|
22 |
|
|
23 |
private static final String CLIENT_ALIAS = "mykey"; |
|
24 |
private static final char[] PASSWORD = "keystore".toCharArray(); |
|
25 |
|
|
26 |
private final Logger logger = LoggerFactory.getLogger(getClass()); |
|
27 |
|
|
28 |
private X509Certificate clientCertificate; |
|
29 |
private KeyPair clientKeyPair; |
|
30 |
|
|
31 |
KeyStoreLoader load(Path baseDir) throws Exception { |
|
32 |
KeyStore keyStore = KeyStore.getInstance("PKCS12"); |
|
33 |
|
|
34 |
Path serverKeyStore = baseDir.resolve("mykey.pfx"); |
|
35 |
|
|
36 |
logger.info("Loading KeyStore at {}", serverKeyStore); |
|
37 |
|
|
38 |
if (Files.exists(serverKeyStore)) { |
|
39 |
try (InputStream in = Files.newInputStream(serverKeyStore)) { |
|
40 |
keyStore.load(in, PASSWORD); |
|
41 |
} |
|
42 |
} |
|
43 |
|
|
44 |
Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD); |
|
45 |
if (serverPrivateKey instanceof PrivateKey) { |
|
46 |
clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS); |
|
47 |
PublicKey serverPublicKey = clientCertificate.getPublicKey(); |
|
48 |
clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey); |
|
49 |
} |
|
50 |
return this; |
|
51 |
} |
|
52 |
X509Certificate getClientCertificate() { |
|
53 |
return clientCertificate; |
|
54 |
} |
|
55 |
KeyPair getClientKeyPair() { |
|
56 |
return clientKeyPair; |
|
57 |
} |
|
58 |
} |