CertificateParsingException: invalid DER-encoded certificate data

     要做一个证书登录的实验。通过后台生成的证书,在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();
	}

之后,就不报错了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值