近來公司需要搭建一個https的服務器來調試接口(服務器用的spring boot框架),剛開始接觸就是一頓百度,最后發現互聯網認可的https安全鏈接的證書需要去CA認證機構申請,由於是調試階段就采用了java的keytool工具來生成密鑰文件,下面是生成密鑰文件的指令和步驟(前提是需要配置好java 的環境變量)。
1、首先打開cmd命令,操作如下:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
1.-storetype 指定密鑰倉庫類型
2.-keyalg 生證書的算法名稱,RSA是一種非對稱加密算法
3.-keysize 證書大小
4.-keystore 生成的證書文件的存儲路徑
5.-validity 證書的有效期
根據提示完成操作,保存在操作時數據內容,最后keystore.p12為生成的密鑰文件
2、打開spring boot 項目工程,將keykeystore.p12文件放到項目的resources根目錄中,同時在application.properties中添加如下代碼:
#你生成的證書名字
server.ssl.key-store=classpath:keystore.p12
# 密鑰庫密碼
server.ssl.key-store-password=第一步生成密鑰文件時輸入的密鑰
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
此時工程的https訪問路徑已經配置好了啟動項目,打開瀏覽器就可以訪問頁面,不過會提示不安全鏈接,主要還是因為證書是不認的。
3、通過java訪問https接口代碼如下:
import java.io.*; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * 通過https訪問服務器忽略證書沒被認可也繼續訪問 */ public class HttpsConnect extends BaseConnect { private static String TAG = "HttpConnect"; private static final class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } protected static byte[] getBytesFromStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] kb = new byte[1024]; int len; while ((len = is.read(kb)) != -1) { baos.write(kb, 0, len); } byte[] bytes = baos.toByteArray(); baos.close(); is.close(); return bytes; } protected static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); byte[] kb = new byte[1024]; int len; while ((len = bais.read(kb)) != -1) { os.write(kb, 0, len); } os.flush(); os.close(); bais.close(); } private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException { SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } SSLSocketFactory ssf = ctx.getSocketFactory(); URL url = new URL(uri); HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(); httpsConn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); httpsConn.setSSLSocketFactory(ssf); httpsConn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); httpsConn.setRequestMethod(method); if("post".equals(method.toLowerCase())) { httpConn.setDoOutput(true); httpConn.setDoInput(true); } return httpsConn; } public static byte[] doGet(String uri) throws IOException { HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET"); return getBytesFromStream(httpsConn.getInputStream()); } public static byte[] doPost(String uri, String data) throws IOException { HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST"); setBytesToStream(httpsConn.getOutputStream(), data.getBytes("UTF-8")); return getBytesFromStream(httpsConn.getInputStream()); } }
import com.mpos.init.Gloabl.DES3Utils;
import com.mpos.init.Gloabl.Global;
import java.io.*;
public class BaseConnect {
protected static byte[] getBytesFromStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] kb = new byte[1024];
int len;
while ((len = is.read(kb)) != -1) {
baos.write(kb, 0, len);
}
byte[] bytes = baos.toByteArray();
baos.close();
is.close();
return bytes;
}
protected static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] kb = new byte[1024];
int len;
while ((len = bais.read(kb)) != -1) {
os.write(kb, 0, len);
}
os.flush();
os.close();
bais.close();
}
/**
* 從輸入流中獲取字節數組
*
* @param inputStream
* @return
* @throws IOException
*/
protected static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[8 * 600];
int len;
byte[] desKey = Global.getDesKey();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byte[] temp = new byte[len];
System.arraycopy(buffer, 0, temp, 0, len);
bos.write(temp);
}
byte[] data = DES3Utils.decryptMode(desKey, bos.toByteArray());
bos.flush();
bos.close();
byte[] result = Global.getSourceData(data);
return result;
}
}
