当我尝试使用证书字符串转换,引发异常(When I try to convert a string

2019-07-29 09:09发布

我有SIGNES文档,并将文档发送,标志和证书到服务器端的applet。 在服务器端门户接收这3个文件,所有文件都存储在Base64格式,但是当我试图获得证书它会引发异常

java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:104)

小应用程序端的代码:

public static byte[] certificate;

public static String getCertificateString() {
        String str = "";
        byte[] result = null;
        result = Base64.encode(certificate);
        for (int i = 0; i < result.length; i++) {
            str += (char) (result[i]);
        }
        return str;
    }

    //initialization of certificate from the store
    Certificate cert = store.getCertificate(aliasKey);
    certificate = cert.toString().getBytes();

在此之后我发证书给Portlet,其中需要验证标志。 但证书转换失败。

portlet代码:

String certificate = request.getParameter("cert");
byte[] cert_array = Base64.decode(certificate.getBytes());
try {
    cert = CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert_array));
}catch(Exception e){
    e.printStackTrace();
}

而在这一点上,在try块,异常升高

Answer 1:

好吧,@ test1604你尝试这样的事情,是实现X509TrustManager类,确定在这里我们去:

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class YouNameClass implements X509TrustManager {... 
   public YouNameClass() {
      super();
   }
}

并添加这个方法,

private static void trustAllHttpsCertificates() throws Exception {
//  Create a trust manager that does not validate certificate chains:
    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
    javax.net.ssl.TrustManager tm = new YouNameClass();
    trustAllCerts[0] = tm; 
    javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

和方法覆盖:

    @Override
     public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
       return;
}

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
       return;
}

    @Override
    public X509Certificate[] getAcceptedIssuers() {
       return null;
}

而已。 :)



Answer 2:

永远不要信任所有证书。 这是非常危险的。 如果你这样做,你可能也不会使用HTTPS,只使用HTTP



文章来源: When I try to convert a string with certificate, Exception is raised