1配置Java环境
将你电脑的Java环境变量配置成AndroidStudio的所使用的Java环境,为什么要配置?这方便等会添加证书的时候是针对AndroidStudio所使用的Java环境(注意:如果你电脑已经配置好了JAVA_HOME,我仍然建议你暂时先配置成AndroidStudio的Java环境,因为不同的Java版本证书可能是不一致的,截止发教程前最新的AndroidStudio3.5.5版本,使用的仍是Java8,但我看到有些人的电脑已经配置到Java11了,如果你已经配置了,请暂时先记录下,然后删除,等你修复好AndroidStudio之后,再配置回来)
(1)将AndroidStudio里的jre配置成JAVA_HOME变量
打开环境变量:此电脑->属性->高级系统设置->高级->环境变量
配置环境变量:系统变量新建JAVA_HOME,输入AndroidStudio目录下Java的环境变量,然后确定保存(如图所示)
然后编辑一下Path环境变量,在Path环境变量分别加入%JAVA_HOME%\bin和%JAVA_HOME%\lib(如图所示)
(2)使用cmd检查当前的java环境,输入where java可查到java.exe所在位置
C:\Users\Administrator>where java
D:\AndroidStudio\jre\bin\java.exe
C:\Users\Administrator>
2.安装证书
2.1桌面新建一个文件夹cert
,在里面新建一个文件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.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host = "10.0.31.32"; //输入服务端地址
int port = 443; //输入服务端端口 一般默认443
String p = "changeit"; //一般默认changeit
char[] passphrase = p.toCharArray();
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);
}
}
}
2.2修改代码
- 在本例中,我在桌面新建了一个Cert文件夹,我把InstallCert.java放到了Cert文件夹中,便于修改和管理
- 修改InstallCert.java代码中"10.0.31.32"为你在AndroidStudio中无法验证证书的域名,改完后应该是下面这样的
String host = "jcenter.bintray.com"; //输入服务端地址
int port = 443; //输入服务端端口 一般默认443
(注意,你的可能是"dl.google.com"或者是"d29vzk4ow07wi7.cloudfront.net",具体的需要看它报错的域名,如果你是第一次安装,请一次性加完三个域名再进行后面的操作,也就是你需要进行三次javac和三次java命令,这样出错的概率会非常低)
2.3获取证书
-
当你修改好并保存文件之后,使用cmd进入到桌面的Cert目录,输入命令javac InstallCert.java,然后按回车来编译它
![<meta charset="utf-8">
-
当你修改好并保存文件之后,使用cmd进入到桌面的Cert目录,输入命令javac InstallCert.java,然后按回车来编译它
- 输入命令java InstallCert,回车进行证书获取,会看到下面这样的结果后,输入回车确认添加证书
- 这是证书添加成功的结果,你会在当前目录得到一个jssecacerts文件,该文件是经过先获取到当前Java环境的证书,然后再将代码中指定网站的证书合并成一个新的证书文件,所以我们后面需要做的是把旧的证书文件替换成我们现在所生成的新证书文件
2.4替换证书文件
<meta charset="utf-8">
打开AndroidStudio的安装目录,进入到jre->jre->lib->security里,将cacerts重命名成cacerts1,然后把jssecacerts拷贝到当前目录,并命名成cacerts
3.刷新AndroidStudio缓存,使配置生效
回到AndroidStudio,选择“File -> Invalidate Caches / Restart”,这个时候,AndroidStudio会自动重启,如果你的Gradle进程没有再运行,并且运行按钮是灰色的,请点击“File -> Sync Project with Gradle Files”
到这一步,问题基本已经解决【请注意,如果你Invalidate Caches / Restart之后,还遇到这个问题,你应该查看错误的域名是不是变了,一般是变成你没添加过的域名,例如:你添加了jcenter.bintrary.com,但你做完以上操作之后,错误的域名变成dl.google.com或者d29vzk4ow07wi7.cloudfront.net,那么你需要再次添加其它域名的证书,一般出现这个错误,那么你通常是要进行三次添加证书操作,然后三次Invalidate Caches / Restart才能解决,如果依旧错误,可能是操作有误,可以加我Q群问问哈,例如有多个java环境,可能会导致你卡在无法使用java InstallCert命令】(完)
作者:Analyas
链接:https://www.jianshu.com/p/89ca5b635d3f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。