您的位置:首页 > 编程语言 > Java开发

CertificateParsingException: invalid DER-encoded certificate data

2014-04-09 11:16 357 查看
     要做一个证书登录的实验。通过后台生成的证书,在web页面进行登录。在后台验证读取证书文件(.cer)时报错,"CertificateParsingException: invalid DER-encoded certificate data!"

  证书生成后的导出证书文件的代码如下:

public static void exportCert(X509Certificate cert, String name, String path)
throws CertificateEncodingException, IOException {
BASE64Encoder base64 = new BASE64Encoder();
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
File certFile = new File(path + File.separator + name + ".cer");
FileOutputStream fos = new FileOutputStream(certFile);

base64.encodeBuffer(cert.getEncoded(), fos);

fos.close();
}

读取证书文件(.cer)的代码的代码如下:

public static Certificate importCer(File certFile) {
Certificate cert = null;
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

FileInputStream fis = new FileInputStream(certFile);

cert = certFactory.generateCertificate(fis);

fis.close();
} catch (Exception exception) {
exception.printStackTrace();
}
return cert;
}

从打印出来的exception来看,应该是证书文件的格式不对。然后,我就检查了一遍代码(导出的代码是网上download的。。),发现在导出时进行了base64的加密处理,

base64.encodeBuffer(cert.getEncoded(), fos);
我估计是这出来问题。然后就把导出证书文件的代码改写了一下,

public static void exportCert(X509Certificate cert, String name, String path)
throws CertificateEncodingException, IOException {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
File certFile = new File(path + File.separator + name + ".cer");
FileOutputStream fos = new FileOutputStream(certFile);
fos.write(cert.getEncoded());
fos.close();
}

之后,就不报错了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Certificate java Exception
相关文章推荐