当我尝试使用证书转换字符串时,会引发异常

时间:2012-05-15 04:03:16

标签: java security applet certificate x509certificate

我有一个applet,用于签署文档,并将文档,签名和证书发送到服务器端。在服务器端portlet接收这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块中,引发了异常

2 个答案:

答案 0 :(得分:0)

好的,@ 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;
}

就是这样。 :)

答案 1 :(得分:0)

不要相信所有证书。那是非常危险的。如果你这样做,你也可以不使用HTTPS,只使用HTTP