生成证书还是比较麻烦的,要用到jdk的一个工具——keytool
首先,创建客户端KeyStore和公钥
在命令行运行:
1、创建私钥和KeyStore: keytool -genkey -alias clientprivatekey -keypass keypass -keystore Client_KeyStore.jks -storepass storepass -dname "CN=tongtech.com,C=CN" -keyalg RSA
创建KeyStore,文件名字为Client_KeyStore.jks,里面有个名为clientprivatekey的私钥。
2、给私钥进行自签名: keytool -selfcert -keystore Client_KeyStore.jks -storepass storepass -alias clientprivatekey -keypass keypass
签名成功,无任何提示。
3、导出私钥
作用是导出的证书将作为公钥保存到TrustStore中。 keytool -export -alias clientprivatekey -file Client_PublicCert.cer -keystore Client_KeyStore.jks -storepass storepass
如果成功,可以看到提示:
保存在文件中的认证 <Client_PublicCert.cer>
然后创建服务端KeyStore
1、创建私钥和KeyStore
2、给私钥进行自签名
3、导出私钥
接下来,将客户端公钥导入到服务端TrustStore中,将服务端公钥导入到客户端TrustStore中。
在命令行中输入:
回车后会提示
引用
所有者:CN=tongtech.com, C=CN
签发人:CN=tongtech.com, C=CN
序列号:4cc7e86c
有效期: Wed Oct 27 16:53:00 CST 2010 至Tue Jan 25 16:53:00 CST 2011
证书指纹:
MD5:FB:AB:71:9F:56:F3:CB:65:16:DC:52:E0:2D:27:FF:F6
SHA1:06:A8:B1:B4:E2:42:9D:B2:F7:99:E7:70:34:08:96:52:E1:CD:4A:76
签名算法名称:SHA1withRSA
版本: 3
信任这个认证? [否]:
打y即可,然后提示
引用
认证已添加至keystore中
同理,将服务端公钥导入到客户端TrustStore中
import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class UTPasswordServerCallBack implements CallbackHandler { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; pc.setPassword("keypass"); System.out.println("Server Identifier=" + pc.getIdentifier()); System.out.println("Server Password=" + pc.getPassword()); } }
import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class UTPasswordClientCallBack implements CallbackHandler { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; pc.setPassword("keypass"); System.out.println("Client Identifier=" + pc.getIdentifier()); System.out.println("Client Password=" + pc.getPassword()); } }