Search in sources :

Example 1 with BASE64Decoder

use of sun.misc.BASE64Decoder in project jdk8u_jdk by JetBrains.

the class ShortRSAKeyGCM method generateSSLContext.

private static SSLContext generateSSLContext(String trustedCertStr, String keyCertStr, String keySpecStr) throws Exception {
    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();
        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }
    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey = (RSAPrivateKey) kf.generatePrivate(priKeySpec);
        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();
        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }
        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }
    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);
    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }
    return ctx;
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) BASE64Decoder(sun.misc.BASE64Decoder) KeyFactory(java.security.KeyFactory) Certificate(java.security.cert.Certificate)

Example 2 with BASE64Decoder

use of sun.misc.BASE64Decoder in project jdk8u_jdk by JetBrains.

the class Obj method decodeReference.

/*
     * Restore a Reference object from several LDAP attributes
     */
private static Reference decodeReference(Attributes attrs, String[] codebases) throws NamingException, IOException {
    Attribute attr;
    String className;
    String factory = null;
    if ((attr = attrs.get(JAVA_ATTRIBUTES[CLASSNAME])) != null) {
        className = (String) attr.get();
    } else {
        throw new InvalidAttributesException(JAVA_ATTRIBUTES[CLASSNAME] + " attribute is required");
    }
    if ((attr = attrs.get(JAVA_ATTRIBUTES[FACTORY])) != null) {
        factory = (String) attr.get();
    }
    Reference ref = new Reference(className, factory, (codebases != null ? codebases[0] : null));
    /*
         * string encoding of a RefAddr is either:
         *
         *      #posn#<type>#<address>
         * or
         *      #posn#<type>##<base64-encoded address>
         */
    if ((attr = attrs.get(JAVA_ATTRIBUTES[REF_ADDR])) != null) {
        String val, posnStr, type;
        char separator;
        int start, sep, posn;
        BASE64Decoder decoder = null;
        ClassLoader cl = helper.getURLClassLoader(codebases);
        /*
             * Temporary Vector for decoded RefAddr addresses - used to ensure
             * unordered addresses are correctly re-ordered.
             */
        Vector<RefAddr> refAddrList = new Vector<>();
        refAddrList.setSize(attr.size());
        for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMore(); ) {
            val = (String) vals.next();
            if (val.length() == 0) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "empty attribute value");
            }
            // first character denotes encoding separator
            separator = val.charAt(0);
            // skip over separator
            start = 1;
            // extract position within Reference
            if ((sep = val.indexOf(separator, start)) < 0) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "separator '" + separator + "'" + "not found");
            }
            if ((posnStr = val.substring(start, sep)) == null) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "empty RefAddr position");
            }
            try {
                posn = Integer.parseInt(posnStr);
            } catch (NumberFormatException nfe) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "RefAddr position not an integer");
            }
            // skip over position and trailing separator
            start = sep + 1;
            // extract type
            if ((sep = val.indexOf(separator, start)) < 0) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "RefAddr type not found");
            }
            if ((type = val.substring(start, sep)) == null) {
                throw new InvalidAttributeValueException("malformed " + JAVA_ATTRIBUTES[REF_ADDR] + " attribute - " + "empty RefAddr type");
            }
            // skip over type and trailing separator
            start = sep + 1;
            // extract content
            if (start == val.length()) {
                // Empty content
                refAddrList.setElementAt(new StringRefAddr(type, null), posn);
            } else if (val.charAt(start) == separator) {
                // Double separators indicate a non-StringRefAddr
                // Content is a Base64-encoded serialized RefAddr
                // skip over consecutive separator
                ++start;
                if (decoder == null)
                    decoder = new BASE64Decoder();
                RefAddr ra = (RefAddr) deserializeObject(decoder.decodeBuffer(val.substring(start)), cl);
                refAddrList.setElementAt(ra, posn);
            } else {
                // Single separator indicates a StringRefAddr
                refAddrList.setElementAt(new StringRefAddr(type, val.substring(start)), posn);
            }
        }
        // Copy to real reference
        for (int i = 0; i < refAddrList.size(); i++) {
            ref.add(refAddrList.elementAt(i));
        }
    }
    return (ref);
}
Also used : BASE64Decoder(sun.misc.BASE64Decoder) Vector(java.util.Vector)

Example 3 with BASE64Decoder

use of sun.misc.BASE64Decoder in project wso2-synapse by wso2.

the class EncodingHelper method decode.

/**
 * Decodes the provided InputStream using the specified encoding type.
 *
 * @param inputStream  The InputStream to decode
 * @param encodingType The encoding to use
 * @return The decoded InputStream
 * @throws java.io.IOException      If an error occurs decoding the input stream
 * @throws IllegalArgumentException if the specified encodingType is not supported
 */
public static InputStream decode(InputStream inputStream, EncodingType encodingType) throws IOException {
    InputStream decodedInputStream = null;
    switch(encodingType) {
        case BASE64:
            if (log.isDebugEnabled()) {
                log.debug("base64 decoding on input  ");
            }
            decodedInputStream = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(inputStream));
            break;
        case BIGINTEGER16:
            if (log.isDebugEnabled()) {
                log.debug("BigInteger 16 encoding on output ");
            }
            BigInteger n = new BigInteger(IOUtils.toString(inputStream), 16);
            decodedInputStream = new ByteArrayInputStream(n.toByteArray());
            break;
        default:
            throw new IllegalArgumentException("Unsupported encoding type");
    }
    return decodedInputStream;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BigInteger(java.math.BigInteger) BASE64Decoder(sun.misc.BASE64Decoder)

Example 4 with BASE64Decoder

use of sun.misc.BASE64Decoder in project portal by ixinportal.

the class HisCertificateController method outpdf.

/**
 * 出证盖章
 *
 * @param serialnumber
 * @param request
 * @param uiModel
 * @return
 * @throws Exception
 */
/*@RequestMapping(value = "/{serialnumber}", method = RequestMethod.POST, produces = "text/html")
	@ResponseBody
	public String seal(@PathVariable("serialnumber") String serialnumber, HttpServletRequest request,
			Model uiModel) throws Exception {
		// EvidenceHisCertificate hisCertificate = new EvidenceHisCertificate();
		Map<String, Object> result = new HashMap<String, Object>();
		// 根据流水号得到出证信息表
		EvidenceHisCertificateExample hiscer = new EvidenceHisCertificateExample();
		EvidenceHisCertificateExample.Criteria tificate = hiscer.createCriteria();
		tificate.andSerialnumberEqualTo(serialnumber);
		EvidenceHisCertificate hisCertificate = sqlSession
				.selectOne("com.itrus.portal.db.EvidenceHisCertificateMapper.selectByExample", hiscer);
		//得到模板信息
		EvidenceOutTemplate outTemplate = sqlSession.selectOne(
				"com.itrus.portal.db.EvidenceOutTemplateMapper.selectByPrimaryKey", hisCertificate.getOutTemplate());
		// 整合证书需要的要素
		String[] factorArr = outTemplate.getFactor().split(",");
		//得到出证关系表
		EvidenceHisRelationshipExample hisrelation = new EvidenceHisRelationshipExample();
		EvidenceHisRelationshipExample.Criteria shipEx = hisrelation.createCriteria();
		shipEx.andHisCertificateEqualTo(hisCertificate.getId());
		List<EvidenceHisRelationship> hisrelationship = sqlSession
				.selectList("com.itrus.portal.db.EvidenceHisRelationshipMapper.selectByExample", hisrelation);
		// 要素核验
		for (EvidenceHisRelationship h : hisrelationship) {
			// 得到基本信息表
			EvidenceBasicInformation basic = sqlSession.selectOne(
					"com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
			result = saveSericece.verifyFactor(basic.getEvidenceSn());
			if (!"1".equals(result.get("status").toString())) {
				result.put("message", result.get("message").toString());
				hisCertificate.setOutState(1);
				hisCertificate.setHisCauseFailure(result.get("message").toString());
				sqlSession.update("com.itrus.portal.db.EvidenceHisCertificateMapper.updateByPrimaryKey",
						hisCertificate);
				return result.get("message").toString();
			}
			// 得到证据附件信息
			EvidenceEnclosureExample enclosureExample = new EvidenceEnclosureExample();
			EvidenceEnclosureExample.Criteria eec = enclosureExample.createCriteria();
			eec.andEvidenceSnEqualTo(basic.getEvidenceSn());
			eec.andPdfTypeEqualTo("1");
			List<EvidenceEnclosure> enclosures = sqlSession
					.selectList("com.itrus.portal.db.EvidenceEnclosureMapper.selectByExample", enclosureExample);

			// 得到提交的要素
			String subFactor = null;
			String lackFactor = null;
			for (EvidenceEnclosure enclosure : enclosures) {
				if (StringUtils.isEmpty(subFactor))
					subFactor = enclosure.getSaveFactor();
				else
					subFactor = subFactor + "," + enclosure.getSaveFactor();
			}
			for (String factor : factorArr) {
				if (!subFactor.contains(factor)) {
					if (StringUtils.isEmpty(lackFactor))
						lackFactor = factor;
					else
						lackFactor = lackFactor + "," + factor;
				}
			}
			if (StringUtils.isNotEmpty(lackFactor)) {
				hisCertificate.setOutState(1);
				hisCertificate.setHisCauseFailure("证据编号:" + basic.getEvidenceSn() + ",缺少必要要素信息:" + lackFactor);
				sqlSession.update("com.itrus.portal.db.EvidenceHisCertificateMapper.updateByPrimaryKey",
						hisCertificate);
				return "证据编号:" + basic.getEvidenceSn() + ",缺少必要要素信息:" + lackFactor;
			}
		}
		result = rtlService.certificationReport(serialnumber);
		if ("0".equals(result.get("status").toString())) {
			
			for (EvidenceHisRelationship h : hisrelationship) {
				// 得到基本信息表
				EvidenceBasicInformation basic = sqlSession.selectOne(
						"com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
				basic.setStatus(2);
				sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
			}
			
			
			hisCertificate.setHisway("2");
			hisCertificate.setHisState("0");
			hisCertificate.setOutState(0);
			sqlSession.update("com.itrus.portal.db.EvidenceHisCertificateMapper.updateByPrimaryKey", hisCertificate);
		} else {
			// hisCertificate.setHisway("2");
			hisCertificate.setOutState(1);
			hisCertificate.setHisCauseFailure(result.get("message").toString());
			sqlSession.update("com.itrus.portal.db.EvidenceHisCertificateMapper.updateByPrimaryKey",
					hisCertificate);
			
			for (EvidenceHisRelationship h : hisrelationship) {
				// 得到基本信息表
				EvidenceBasicInformation basic = sqlSession.selectOne(
						"com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
				basic.setStatus(4);
				sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
			}

		}

		return "核验成功";
	}*/
/**
 * 下载pdf
 *
 * @param serialnumber
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/outpdf/{serialnumber}")
public String outpdf(@PathVariable("serialnumber") String serialnumber, HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        EvidenceHisCertificateExample hiscer = new EvidenceHisCertificateExample();
        EvidenceHisCertificateExample.Criteria tificate = hiscer.createCriteria();
        tificate.andSerialnumberEqualTo(serialnumber);
        EvidenceHisCertificate hisCertificate = sqlSession.selectOne("com.itrus.portal.db.EvidenceHisCertificateMapper.selectByExample", hiscer);
        // 得到服务编码
        AppService appservice = appService.selectById(hisCertificate.getHisAppService());
        // 得到出证服务配置
        EvidenceOutServiceConfigExample saveService = new EvidenceOutServiceConfigExample();
        EvidenceOutServiceConfigExample.Criteria saveServiceEx = saveService.createCriteria();
        saveServiceEx.andAppServiceEqualTo(appservice.getId());
        EvidenceOutServiceConfig outService = sqlSession.selectOne("com.itrus.portal.db.EvidenceOutServiceConfigMapper.selectByExample", saveService);
        String footer = getClass().getClassLoader().getResource("").getPath() + File.separator + "footer.html";
        String header = getClass().getClassLoader().getResource("").getPath() + File.separator + "header.html";
        // 得到出证模板信息
        EvidenceOutTemplate outTmplate = sqlSession.selectOne("com.itrus.portal.db.EvidenceOutTemplateMapper.selectByPrimaryKey", outService.getOutReportTemplate());
        // 拼接url路径
        String url = systemConfigService.getTsAddress() + "/" + outTmplate.getFile() + "/" + serialnumber;
        log.error("123url321=" + url);
        /*
			 * String base64 = Pdf.html2pdf(outTmplate.getFile(),
			 * systemConfigService.getpdfurl() + "/" + serialnumber + ".pdf",
			 * header, footer);// 下载未签章证书
			 */
        String base64 = Pdf.html2pdf(url, systemConfigService.getpdfurl() + "/" + serialnumber + ".pdf", header, // 下载未签章证书
        footer);
        String fileName = "" + Calendar.getInstance().getTimeInMillis();
        fileName = reportTemplate.chineseUtf(fileName, request);
        // String filename = "存证服务统计信息" + new
        // SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".pdf";
        response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".pdf").getBytes("utf-8"), "iso-8859-1"));
        // response.setHeader("Content-disposition", "attachment;filename="
        // +
        // fileName);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        if (base64 == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] bytes = decoder.decodeBuffer(base64);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {
                // 调整异常数据
                bytes[i] += 256;
            }
        }
        // 生成文件的路径
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
        return null;
    } catch (Exception e) {
        return null;
    }
}
Also used : AppService(com.itrus.portal.db.AppService) EvidenceOutServiceConfigExample(com.itrus.portal.db.EvidenceOutServiceConfigExample) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) EvidenceHisCertificate(com.itrus.portal.db.EvidenceHisCertificate) EvidenceOutServiceConfig(com.itrus.portal.db.EvidenceOutServiceConfig) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) EvidenceHisCertificateExample(com.itrus.portal.db.EvidenceHisCertificateExample) EvidenceOutTemplate(com.itrus.portal.db.EvidenceOutTemplate) BASE64Decoder(sun.misc.BASE64Decoder) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with BASE64Decoder

use of sun.misc.BASE64Decoder in project portal by ixinportal.

the class BasicInformationController method download.

/**
 * 下载回执报告
 *
 * @param evidenceSn
 * @param request
 * @param response
 * @param uiModel
 * @return
 * @throws Exception
 */
@RequestMapping(value = "outpdf/{evidenceSn}")
public String download(@PathVariable("evidenceSn") String evidenceSn, HttpServletRequest request, HttpServletResponse response, Model uiModel) throws Exception {
    RealNameAuthentication realNameAuthentication = CacheCustomer.getAUTH_CONFIG_MAP().get(2);
    String fileName = null;
    if (realNameAuthentication == null) {
        realNameAuthentication = realNameAuthenticationSerivce.getRealNameAuthenticationByTwo();
    }
    try {
        if (realNameAuthentication == null) {
            String oper = "下载回执报告失败";
            String info = "失败原因:服务器出错,请联系管理员";
            LogUtil.evidencelog(sqlSession, null, oper, info);
            return "服务器出错,请联系管理员";
        }
        // 得到接口路径
        String urlAgent = realNameAuthentication.getRealNameddress();
        EvidenceEnclosureExample enclo = new EvidenceEnclosureExample();
        EvidenceEnclosureExample.Criteria enclosureEx = enclo.createCriteria();
        enclosureEx.andEvidenceSnEqualTo(evidenceSn);
        enclosureEx.andPdfTypeEqualTo("3");
        EvidenceEnclosure enclosure = sqlSession.selectOne("com.itrus.portal.db.EvidenceEnclosureMapper.selectByExample", enclo);
        if (enclosure == null) {
            return "未找到该证据编号的信息";
        }
        String base64 = EvidenceSaveServiceApi.decryptedAndDownload(sqlSession, enclosure.getBuid(), urlAgent);
        response.reset();
        fileName = Calendar.getInstance().getTimeInMillis() + "";
        fileName = reportTemplate.chineseUtf(fileName, request);
        response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".pdf").getBytes("utf-8"), "iso-8859-1"));
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        if (base64 == null || base64.contains("exception")) {
            String oper = "下载回执报告失败";
            String info = "失败原因:base64为空";
            LogUtil.evidencelog(sqlSession, null, oper, info);
            return "base64为空";
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    // 调整异常数据
                    bytes[i] += 256;
                }
            }
            // FileOutputStream out = new
            // FileOutputStream("D:/test/itext/123.pdf");
            // 生成文件的路径
            OutputStream out = response.getOutputStream();
            // OutputStream os = new
            // BufferedOutputStream(response.getOutputStream());
            out.write(bytes);
            out.flush();
            out.close();
            String oper = "下载回执报告成功";
            String info = "报告名称:" + fileName + ".pdf";
            LogUtil.evidencelog(sqlSession, null, oper, info);
        } catch (Exception e) {
            String oper = "下载回执报告失败";
            String info = "失败原因:" + e.getMessage();
            LogUtil.evidencelog(sqlSession, null, oper, info);
            return e.getMessage();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch
        e.printStackTrace();
        String oper = "下载回执报告失败";
        String info = "失败原因:" + e.getMessage();
        LogUtil.evidencelog(sqlSession, null, oper, info);
    }
    return null;
}
Also used : BufferedOutputStream(java.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) EvidenceEnclosureExample(com.itrus.portal.db.EvidenceEnclosureExample) EvidenceEnclosure(com.itrus.portal.db.EvidenceEnclosure) RealNameAuthentication(com.itrus.portal.db.RealNameAuthentication) BASE64Decoder(sun.misc.BASE64Decoder) JSONException(org.json.JSONException) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

BASE64Decoder (sun.misc.BASE64Decoder)44 IOException (java.io.IOException)23 ByteArrayInputStream (java.io.ByteArrayInputStream)6 FileOutputStream (java.io.FileOutputStream)6 HashMap (java.util.HashMap)6 OutputStream (java.io.OutputStream)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 JSONObject (com.alibaba.fastjson.JSONObject)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 InvalidKeyException (java.security.InvalidKeyException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 BASE64Encoder (sun.misc.BASE64Encoder)4 UserInfoServiceException (com.itrus.portal.exception.UserInfoServiceException)3 FileNotFoundException (java.io.FileNotFoundException)3 URL (java.net.URL)3 KeyFactory (java.security.KeyFactory)3 CertificateException (java.security.cert.CertificateException)3 Map (java.util.Map)3 Cipher (javax.crypto.Cipher)3