前提,把证书放到Android Studio 工程中的 assets 目录下 :
安装cer证书 :
/**
* 安裝证书
*/
public void installCert(Context context,String cerName, String name) {
InputStream assetsIn = null;
Intent intent = KeyChain.createInstallIntent();
try {
//获取证书流,注意参数为assets目录文件全名
assetsIn = context.getAssets().open(cerName);
byte[] cert = new byte[10240];
assetsIn.read(cert);
javax.security.cert.X509Certificate x509 = null;
try {
x509 = javax.security.cert.X509Certificate.getInstance(cert);
//将证书传给系统
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, x509.getEncoded());
} catch (CertificateEncodingException e) {
e.printStackTrace();
} catch (javax.security.cert.CertificateException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
//此处为给证书设置默认别名,第二个参数可自定义,设置后无需用户输入
intent.putExtra("name", name);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
NsLog.e(TAG,"安装证书异常");
}
}
安装 pfx 格式证书 :
先要把证书,拷到应用私有目录或sd卡目录中,然后进行安装
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File filesDir = mContext.getFilesDir();
File file = new File(filesDir, "test.pfx");
// 通过FileProvider 提供给系统
Uri uri = FileProvider.getUriForFile(mContext, "xxx.xxx.xxx.fileprovider",file);
Log.e(TAG,"URI :"+uri);
intent.setDataAndType(uri, "application/x-pkcs12");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
联系方式 :Q 262184018
如果觉得文章有用,帮忙点个喜欢❤️ ,😘😘😘 赠人玫瑰,手留余香