最近项目组有调用https的接口,所以在网上找了一圈关于linux下https证书的相关的文章。找到如下的步骤,自己真的使用,总结一下,方便以后查阅.
- 有些https需要安装证书,才可以调用,有些不安装也能调用。下面说必须安装证书时,怎么办。
- 执行java InstallCert 域名:端口,输入1,按下回车,在当前目录生成jssecacerts文件,他是keystore。该keystore的密码是空。
- 把jssecacerts放到$JAVA_HOME/jre/lib/security目录下,或者通过以下方式:
System.setProperty(“javax.net.ssl.trustStore”, “你的jssecacerts证书路径”);
接下来对证书的操作
keytool -list -keystore jssecacerts 查看密钥库里面的证, 不出意外的话会有很多证书指纹
keytool -list -keystore jssecacerts | grep /i ***alias(名称)*** 查找我们自己的
keytool -export -alias ***alias(名称)*** -file Server.crt -keystore jssecacerts 会在当前目录生成Server.crt
导入到java的认证文件夹下keytool -import -file Server.cer -keystore “%JAVA_HOME%\jre\lib\security\cacerts” -alias server
使用如下命令可以看到结果:
keytool -list -keystore “%JAVA_HOME%\jre\lib\security\cacerts” | grep Server
到这里签名证书制作完成了就可以使用restful请求https服务了,
注意:因为是静态加载,所以要重新启动你的Web Server,证书才能生效。
=================================================
详细步骤:
把如下内容保存为InstallCert.java,执行javac InstallCert.java进行编译.
/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCert [:port] [passphrase]");
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println (" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println ("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'"); } private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}
执行:java InstallCert hostname,比如:
java InstallCert www.baidu.com
会看到如下信息:
Loading KeyStore jssecacerts...
Opening connection to www.baidu.com:443...
Starting SSL handshake...
javax.net.ssl.SSLException: java.lang.UnsupportedOperationException
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1862)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1845)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1366)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at InstallCert.main(InstallCert.java:87)
Caused by: java.lang.UnsupportedOperationException
at InstallCert$SavingTrustManager.getAcceptedIssuers(InstallCert.java:171)
at sun.security.ssl.AbstractTrustManagerWrapper.checkAlgorithmConstraints(SSLContextImpl.java:998)
at sun.security.ssl.AbstractTrustManagerWrapper.checkAdditionalTrust(SSLContextImpl.java:944)
at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:886)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:901)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:837)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
... 2 more
Server sent 3 certificate(s):
1 Subject CN=baidu.com, OU=service operation department., O="BeiJing Baidu Netcom Science Technology Co., Ltd", L=beijing, ST=beijing, C=CN
Issuer CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
sha1 b5 02 43 62 75 c8 87 4f 10 23 db 92 e3 04 72 dd 59 71 59 e0
md5 b2 ac 71 df 1f d6 1d d9 a2 83 8d 86 ef 86 58 e4
2 Subject CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
Issuer CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
sha1 ff 67 36 7c 5c d4 de 4a e1 8b cc e1 d7 0f da bd 7c 86 61 35
md5 23 d5 85 8e bc 89 86 10 7c b7 ac 1e 17 f7 26 c5
3 Subject CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
Issuer OU=Class 3 Public Primary Certification Authority, O="VeriSign, Inc.", C=US
sha1 32 f3 08 82 62 2b 87 cf 88 56 c6 3d b8 73 df 08 53 b4 dd 27
md5 f9 1f fe e6 a3 6b 99 88 41 d4 67 dd e5 f8 97 7a
Enter certificate to add to trusted keystore or 'q' to quit: [1]
输入1,回车,然后会在当前的目录下产生一个名为“ssecacerts”的证书。
将证书拷贝到$JAVA_HOME/jre/lib/security目录下,或者通过以下方式:
System.setProperty(“javax.net.ssl.trustStore”, “你的jssecacerts证书路径”);
执行如下命令生产证书文件
keytool -export -alias ***alias(名称)*** -file Server.crt -keystore jssecacerts
会在当前目录生成Server.crt,接着把证书添加的信任目录
keytool -import -file Server.crt -keystore “%JAVA_HOME%\jre\lib\security\cacerts” -alias server
会要求输入你的密码,直接输入123456两次后,在输入yes,提示安装成功
Enter keystore password:
Re-enter new password:
Owner: CN=baidu.com, OU=service operation department., O="BeiJing Baidu Netcom Science Technology Co., Ltd", L=beijing, ST=beijing, C=CN
Issuer: CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
Serial number: 1a00c5992a0a1426f751433bd5cbf
Valid from: Mon Aug 15 08:00:00 CST 2016 until: Thu Aug 17 07:59:59 CST 2017
Certificate fingerprints:
MD5: B2:AC:71:DF:1F:D6:1D:D9:A2:83:8D:86:EF:86:58:E4
SHA1: B5:02:43:62:75:C8:87:4F:10:23:DB:92:E3:04:72:DD:59:71:59:E0
SHA256: 55:60:63:D5:7A:25:A5:60:02:1B:22:DE:23:B6:7A:59:0F:D3:98:C0:B7:7D:DC:33:1E:79:D7:7F:4B:22:07:12
Signature algorithm name: SHA256withRSA
Version: 3
Extensions:
#1: ObjectId: 1.3.6.1.4.1.11129.2.4.2 Criticality=false
0000: 04 81 F3 00 F1 00 77 00 DD EB 1D 2B 7A 0D 4F A6 ......w....+z.O.
0010: 20 8B 81 AD 81 68 70 7E 2E 8E 9D 01 D5 5C 88 8D ....hp......\..
0020: 3D 11 C4 CD B6 EC BE CC 00 00 01 56 90 7E 47 3A =..........V..G:
0030: 00 00 04 03 00 48 30 46 02 21 00 93 2D 3C E8 DC .....H0F.!..-<..
0040: 36 2B D6 FD EA 83 0D F4 07 FD FB 1B 38 12 4F E8 6+..........8.O.
0050: 97 A9 9B 56 8F 51 63 56 B6 B0 CD 02 21 00 CC 54 ...V.QcV....!..T
0060: 7A BB A8 E9 B2 CB 9A 5A AC 13 88 56 61 C0 CE BB z......Z...Va...
0070: C8 62 BC 92 B8 4D E7 D3 D4 D0 E1 6F 4E C3 00 76 .b...M.....oN..v
0080: 00 A4 B9 09 90 B4 18 58 14 87 BB 13 A2 CC 67 70 .......X......gp
0090: 0A 3C 35 98 04 F9 1B DF B8 E3 77 CD 0E C8 0D DC .<5.......w.....
00A0: 10 00 00 01 56 90 7E 47 5A 00 00 04 03 00 47 30 ....V..GZ.....G0
00B0: 45 02 20 1F 44 21 BD 58 62 8B 42 12 DC 3E 0E 43 E. .D!.Xb.B..>.C
00C0: BF EF 0C A9 4B 25 1D E7 39 6B 03 3C 6A 14 C1 E1 ....K%..9k.<j...
00D0: 8D 1D 77 02 21 00 8C EE CB 42 41 52 C4 E6 93 E1 ..w.!....BAR....
00E0: 20 E4 0A E8 6C FA A0 5D 81 5C D6 59 57 45 C7 98 ...l..].\.YWE..
00F0: E2 E4 D9 88 04 99 ......
#2: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[
accessMethod: ocsp
accessLocation: URIName: http://ss.symcd.com
,
accessMethod: caIssuers
accessLocation: URIName: http://ss.symcb.com/ss.crt
]
]
#3: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 5F 60 CF 61 90 55 DF 84 43 14 8A 60 2A B2 F5 7A _`.a.U..C..`*..z
0010: F4 43 18 EF .C..
]
]
#4: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:false
PathLen: undefined
]
#5: ObjectId: 2.5.29.31 Criticality=false
CRLDistributionPoints [
[DistributionPoint:
[URIName: http://ss.symcb.com/ss.crl]
]]
#6: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
[CertificatePolicyId: [2.23.140.1.2.2]
[PolicyQualifierInfo: [
qualifierID: 1.3.6.1.5.5.7.2.1
qualifier: 0000: 16 17 68 74 74 70 73 3A 2F 2F 64 2E 73 79 6D 63 ..https://d.symc
0010: 62 2E 63 6F 6D 2F 63 70 73 b.com/cps
], PolicyQualifierInfo: [
qualifierID: 1.3.6.1.5.5.7.2.2
qualifier: 0000: 30 19 0C 17 68 74 74 70 73 3A 2F 2F 64 2E 73 79 0...https://d.sy
0010: 6D 63 62 2E 63 6F 6D 2F 72 70 61 mcb.com/rpa
]] ]
]
#7: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
serverAuth
clientAuth
]
#8: ObjectId: 2.5.29.15 Criticality=true
KeyUsage [
DigitalSignature
Key_Encipherment
]
#9: ObjectId: 2.5.29.17 Criticality=false
SubjectAlternativeName [
DNSName: *.baidu.com
DNSName: *.baifubao.com
DNSName: *.bdstatic.com
DNSName: *.hao123.com
DNSName: *.nuomi.com
DNSName: *.bce.baidu.com
DNSName: *.eyun.baidu.com
DNSName: *.map.baidu.com
DNSName: baidu.com
DNSName: baifubao.com
DNSName: www.baidu.cn
DNSName: www.baidu.com.cn
DNSName: click.hm.baidu.com
DNSName: log.hm.baidu.com
DNSName: cm.pos.baidu.com
DNSName: wn.pos.baidu.com
DNSName: update.pan.baidu.com
DNSName: mct.y.nuomi.com
]
Trust this certificate? [no]: yes
Certificate was added to keystore
注意:因为是静态加载,所以要重新启动你的应用,证书才能生效。9