我有一个.crt文件,我想使用Java导入密钥库和信任库(首先创建密钥库和信任库,然后导入)。
下面是我正在使用的代码:
import org.glassfish.tyrus.client.ClientManager;
import org.glassfish.tyrus.client.ClientProperties;
import org.glassfish.tyrus.client.SslContextConfigurator;
import org.glassfish.tyrus.client.SslEngineConfigurator;
@ClientEndpoint
public class test {
private static CountDownLatch latch;
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
logger.info("Connected ... " + session.getId());
try {
session.getBasicRemote().sendText("start");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnMessage
public String onMessage(String message, Session session) {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try {
logger.info("Received ...." + message);
String userInput = bufferRead.readLine();
return userInput;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(test.class, new URI("wss://x.x.x.x:8085"));
latch.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
我正在使用tyrus websocket客户端,因此,我需要添加以下属性:
final ClientManager client = ClientManager.createClient();
System.getProperties().put("javax.net.debug", "all");
System.getProperties().put(SSLContextConfigurator.KEY_STORE_FILE, "...");
System.getProperties().put(SSLContextConfigurator.TRUST_STORE_FILE, "...");
System.getProperties().put(SSLContextConfigurator.KEY_STORE_PASSWORD, "...");
System.getProperties().put(SSLContextConfigurator.TRUST_STORE_PASSWORD, "...");
final SSLContextConfigurator defaultConfig = new SSLContextConfigurator();
defaultConfig.retrieve(System.getProperties());
// or setup SSLContextConfigurator using its API.
SSLEngineConfigurator sslEngineConfigurator =
new SSLEngineConfigurator(defaultConfig, true, false, false);
client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR,
sslEngineConfigurator);
client.connectToServer(... , ClientEndpointConfig.Builder.create().build(),
new URI("wss://localhost:8181/sample-echo/echo"));
}
因此,如何创建密钥库和信任库并将.crt导入到其中。
答案 0 :(得分:0)
我通过将.crt文件直接导入到Java密钥库中解决了上述问题:
用于导入Java密钥库
keytool -trustcacerts -keystore "/jdk/jre/lib/security/cacerts" -storepass changeit -importcert -alias testalias -file "/opt/ssl/test.crt"
通过使用以上命令,将对服务器证书进行评估并建立连接,但是如果要创建新的密钥库并导入.crt,则意味着使用以下命令将创建.jks类型的密钥库。
用于创建密钥库并导入.crt
keytool -import -alias testalias -file test.crt -keypass keypass -keystore test.jks -storepass test@123
此处
keystore password : test@123
keypass : keypass
由于一些代码将进行验证,并且如果您使用的是wss / https,它将要求密钥库/信任库配置,那么您可以使用步骤2中提到的上述配置(创建密钥库并导入.crt)。否则,step1(导入到Java密钥库中)就足够了。