package com.iailab.module.data.channel.opcua.collector;
|
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.io.InputStream;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.security.*;
|
import java.security.cert.X509Certificate;
|
import java.util.regex.Pattern;
|
|
/**
|
* @author PanZhibao
|
* @Description
|
* @createTime 2022年07月22日 14:44:00
|
*/
|
public class KeyStoreLoader {
|
|
private static final Pattern IP_ADDR_PATTERN = Pattern.compile(
|
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
|
|
private static final String CLIENT_ALIAS = "mykey";
|
private static final char[] PASSWORD = "keystore".toCharArray();
|
|
private final Logger logger = LoggerFactory.getLogger(getClass());
|
|
private X509Certificate clientCertificate;
|
private KeyPair clientKeyPair;
|
|
KeyStoreLoader load(Path baseDir) throws Exception {
|
KeyStore keyStore = KeyStore.getInstance("PKCS12");
|
|
Path serverKeyStore = baseDir.resolve("mykey.pfx");
|
|
logger.info("Loading KeyStore at {}", serverKeyStore);
|
|
if (Files.exists(serverKeyStore)) {
|
try (InputStream in = Files.newInputStream(serverKeyStore)) {
|
keyStore.load(in, PASSWORD);
|
}
|
}
|
|
Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
|
if (serverPrivateKey instanceof PrivateKey) {
|
clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS);
|
PublicKey serverPublicKey = clientCertificate.getPublicKey();
|
clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
|
}
|
return this;
|
}
|
X509Certificate getClientCertificate() {
|
return clientCertificate;
|
}
|
KeyPair getClientKeyPair() {
|
return clientKeyPair;
|
}
|
}
|