Search in sources :

Example 1 with CertInfo

use of cn.topca.tca.ra.service.CertInfo in project portal by ixinportal.

the class DownLoadCertWebController method downloadPfxCert.

/**
 * 用户下载pfx证书的接口
 * @param id,订单id
 * @param session
 * @param request
 * @param response
 * @return
 */
@RequestMapping("/pfx/{id}")
public String downloadPfxCert(@PathVariable(value = "id") Long id, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    UserInfo webuserInfo = (UserInfo) session.getAttribute("webuserInfo");
    Enterprise webenterprise = (Enterprise) session.getAttribute("webenterprise");
    if (null == webuserInfo || null == webenterprise) {
        return null;
    }
    Integer uidIdx = 1;
    Bill bill = billService.getBill(id);
    if (null == bill) {
        return null;
    }
    boolean billFlag = webuserInfo.getId().equals(bill.getUniqueId()) && webenterprise.getId().equals(bill.getEnterprise());
    if (!billFlag) {
        return null;
    }
    // 用户已经下载过了,再次下载
    boolean downLoadFlag = bill.getBillStatus().equals(ComNames.BILL_STATUS_6) || bill.getBillStatus().equals(ComNames.BILL_STATUS_7) || bill.getBillStatus().equals(ComNames.BILL_STATUS_8);
    if (downLoadFlag) {
        // 根据订单号,找到订单对应的证书信息
        CertBuf certBuf = sqlSession.selectOne("com.itrus.portal.db.CertBufMapper.selectPfxCertByBillId", bill.getId());
        Date date = new Date();
        // 获取证书第一次下载时间和当前时间比较,如果超过了十五天,则不允许下载
        int day = DateUtils.daysOfTwo(date, certBuf.getCreateTime());
        if (day > 16) {
            return null;
        }
        // 从数据库中取出数据,返回给客户端.
        // 重置response对象中的缓冲区,该方法可以不写,但是你要保证response缓冲区没有其他数据,否则导出可能会出现问题,建议加上
        response.reset();
        String filename = webenterprise.getEnterpriseName() + "功能证书.pfx";
        filename = encodeFilename(filename, request);
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        response.setCharacterEncoding("utf-8");
        // 由于导出格式是pfx的文件,设置导出文件的响应头部信息
        response.setContentType("application/x-pkcs12");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            // 清理刷新缓冲区,将缓存中的数据将数据导出excel
            byte[] byteCert = Base64.decode(certBuf.getPfxCert());
            os.write(byteCert);
            os.flush();
            // 关闭os
            if (os != null) {
                os.close();
            }
            certBuf.setLastDownloadTime(new Date());
            certBuf.setCertDownloadNumber(certBuf.getCertDownloadNumber() + 1);
            downLoadCertService.updatePfxCert(certBuf);
            // 记录日志
            UserLog userlog = new UserLog();
            userlog.setProject(webuserInfo.getProject());
            userlog.setType("用户下载证书pfx");
            userlog.setInfo(webenterprise.getEnterpriseName() + "下载证书成功");
            userlog.setHostId("未知");
            userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
            LogUtil.userlog(sqlSession, userlog);
            return null;
        } catch (IOException e) {
            UserLog userlog = new UserLog();
            userlog.setProject(bill.getProject());
            userlog.setType("用户下载证书pfx");
            userlog.setInfo(webenterprise.getEnterpriseName() + "失败,错误信息:" + e.getMessage());
            userlog.setHostId("未知");
            userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
            LogUtil.userlog(sqlSession, userlog);
        }
    } else {
        // 用户未下载过,第一次下载
        if (bill.getBillStatus().equals(ComNames.BILL_STATUS_13)) {
            // 查询项目产品
            Product product = productService.getProduct(bill.getProduct());
            // 企业
            Enterprise enterprise = enterpriseService.getEnterpriseById(bill.getEnterprise());
            // 获取产品、RA配置
            RaAccount ra = raAccountService.getRaAccount(product.getRa());
            // 证书配置
            DigitalCert digitalcert = digitalCertService.getDigitalCert(product.getCert());
            // 下载证书
            String autoidType = "";
            Integer autoidValue = 0;
            String pfxCert = "";
            // 用户ID,用来最终匹配公钥证书和密钥对
            String userid = bill.getBillId() + (Math.random() * 1000 + 9000);
            // TODO 20170410pfx私钥证书保护密码:需要根据产品配置的密码或获取
            String certPass = product.getPassword();
            // 产生CSR证书请求
            String certReqBuf = "";
            // 算法
            String algorithm = digitalCertService.getAlgorithm(digitalcert);
            // 下载证书
            CertInfo racertinfo = null;
            try {
                certReqBuf = GenUtil.GenP10(userid, "", algorithm);
                racertinfo = downLoadCertService.downLoadCert(product, ra, bill, digitalcert, uidIdx, certReqBuf, autoidType, autoidValue);
                // pfxCert = GenUtil.GenPFX(userid, certPass,
                // racertinfo.getCertSignBuf(), false);
                // pfxCert = GenUtil2.GenPFX(userid, certPass, racertinfo.getCertSignBuf(), pfxCert, false, enterprise.getEnterpriseName());
                pfxCert = GenUtil.GenPFX(userid, certPass, racertinfo.getCertSignBuf(), false, enterprise.getEnterpriseName());
                // 保存证书
                downLoadCertService.savePfxCertInfo(racertinfo, bill, ra.getId(), uidIdx, "", autoidType, autoidValue, pfxCert);
                // 从数据库中取出数据,返回给客户端.
                // 重置response对象中的缓冲区,该方法可以不写,但是你要保证response缓冲区没有其他数据,否则导出可能会出现问题,建议加上
                response.reset();
                String filename = webenterprise.getEnterpriseName() + "通讯证书.pfx";
                filename = encodeFilename(filename, request);
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
                response.setCharacterEncoding("utf-8");
                // 由于导出格式是pfx的文件,设置导出文件的响应头部信息
                response.setContentType("application/x-pkcs12");
                OutputStream os = null;
                os = response.getOutputStream();
                // 清理刷新缓冲区,将缓存中的数据将数据导出excel
                byte[] byteCert = Base64.decode(pfxCert);
                os.write(byteCert);
                os.flush();
                // 关闭os
                if (os != null) {
                    os.close();
                }
                // 记录日志
                UserLog userlog = new UserLog();
                userlog.setProject(bill.getProject());
                userlog.setType("用户下载证书pfx");
                userlog.setInfo(webenterprise.getEnterpriseName() + "下载证书成功,企业名称:" + webenterprise.getEnterpriseName());
                userlog.setHostId("未知");
                userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
                LogUtil.userlog(sqlSession, userlog);
                return null;
            } catch (Exception e) {
                // 记录日志
                UserLog userlog = new UserLog();
                userlog.setProject(bill.getProject());
                userlog.setType("用户下载证书pfx");
                userlog.setInfo(webenterprise.getEnterpriseName() + "失败,错误信息:" + e.getMessage());
                userlog.setHostId("未知");
                userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
                LogUtil.userlog(sqlSession, userlog);
            }
        }
    }
    return null;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) OutputStream(java.io.OutputStream) Product(com.itrus.portal.db.Product) UserInfo(com.itrus.portal.db.UserInfo) UserLog(com.itrus.portal.db.UserLog) IOException(java.io.IOException) Date(java.util.Date) GenP10Exception(com.itrus.Exception.GenP10Exception) IOException(java.io.IOException) DigitalCert(com.itrus.portal.db.DigitalCert) RaAccount(com.itrus.portal.db.RaAccount) Enterprise(com.itrus.portal.db.Enterprise) Bill(com.itrus.portal.db.Bill) CertBuf(com.itrus.portal.db.CertBuf) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with CertInfo

use of cn.topca.tca.ra.service.CertInfo in project portal by ixinportal.

the class CertService method sm2.

/**
 * 制证
 */
@RequestMapping(value = "/make/sm2")
@ResponseBody
public Map<String, Object> sm2(@RequestParam("csr") String csr, @RequestParam("userName") String userName, @RequestParam("userEmail") String userEmail, @RequestParam(value = "period", required = false) Integer period) {
    Map<String, Object> result = new HashMap<String, Object>(3);
    result.put("status", 0);
    try {
        CertUtlis certutil = new CertUtlis();
        UserInfo rauserinfo = new UserInfo();
        rauserinfo.setUserName(userName);
        rauserinfo.setUserEmail(userEmail);
        // 证书有效期
        Integer certValidity = 7;
        if ("0".equals(period)) {
            certValidity = null;
        } else if (1 == period) {
            certValidity = 365 * 1 + 1;
        } else if (3 == period) {
            certValidity = 365 * 3 + 1;
        } else if (5 == period) {
            certValidity = 365 * 5 + 2;
        } else if (10 == period) {
            certValidity = 365 * 10 + 2;
        }
        // 调用RA
        CertInfo racertinfo = null;
        RaAccount ra = new RaAccount();
        ra.setAaPassword("password");
        ra.setServiceUrl("http://topca-ra.itrus.com.cn/services/userAPI?wsdl");
        ra.setAccountOrganization("i信部门SM2双证书的测试");
        ra.setAccountOrgUnit("i信部门测试");
        String accountHash = CipherUtils.md5((ra.getAccountOrganization() + ra.getAccountOrgUnit()).getBytes("GBK")).toUpperCase();
        ra.setAccountHash(accountHash);
        racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
        Map<String, Object> data = new HashMap<String, Object>(8);
        data.put("certSignBuf", racertinfo.getCertSignBuf());
        data.put("certChain", racertinfo.getCertSignBufP7());
        data.put("certDn", racertinfo.getCertSubjectDn());
        data.put("certSn", racertinfo.getCertSerialNumber());
        data.put("issuerDn", racertinfo.getCertIssuerDn());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        data.put("startTime", sdf.parse(racertinfo.getCertNotBefore()));
        data.put("endTime", sdf.parse(racertinfo.getCertNotAfter()));
        data.put("certKmcRep1", racertinfo.getCertKmcRep1());
        data.put("certKmcRep2", racertinfo.getCertKmcRep2());
        result.put("data", data);
        result.put("status", 1);
        result.put("message", "制作证书成功");
    } catch (Exception e) {
        e.printStackTrace();
        result.put("message", e.toString());
    // String oper = "RA调用失败";
    // String info = "错误原因:" + e.toString();
    // com.itrus.portal.evidence.utils.LogUtil.evidencelog(sqlSession, oper, info);
    }
    return result;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) HashMap(java.util.HashMap) JSONObject(com.alibaba.fastjson.JSONObject) UserInfo(cn.topca.tca.ra.service.UserInfo) SimpleDateFormat(java.text.SimpleDateFormat) ParseException(java.text.ParseException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with CertInfo

use of cn.topca.tca.ra.service.CertInfo in project portal by ixinportal.

the class RenewUserCertWebController method updateCert.

@RequestMapping(value = "/updateCert", method = RequestMethod.POST)
// TODO 更新证书
@ResponseBody
public Map<String, Object> updateCert(// 证书序列号
@RequestParam(value = "certSn", required = true) String certSn, // 旧的证书的请求,目前随便写:45564
@RequestParam(value = "csr", required = true) String csr, // 证书base64
@RequestParam(value = "crt", required = true) String crt, // 原证书所在容器生成的新的证书请求
@RequestParam(value = "newCSR", required = true) String newCSR, // 老证书对csr签名后的base64字符串
@RequestParam(value = "pkcs7", required = true) String pkcs7, // 订单id
@RequestParam(value = "billid", required = true) Long billId, // 证书所属的keysn,没有key则为""
@RequestParam(value = "keySn", required = false) String keySn, @RequestParam(value = "oldCertDn", required = false) String oldCertDn, Model uimModel, HttpSession session) {
    // TODO,参数有效性验证
    Map<String, Object> ret = new HashMap<String, Object>();
    ret.put("status", 1);
    UserInfo webuserInfo = (UserInfo) session.getAttribute("webuserInfo");
    Enterprise webenterprise = (Enterprise) session.getAttribute("webenterprise");
    if (null == webuserInfo || null == webenterprise) {
        // 2标识登录已经失效,需跳转到登录页面
        ret.put("retCode", 2);
        ret.put("retMsg", "登录状态失效");
        return ret;
    }
    Bill bill = billService.getBill(billId);
    if (null == bill) {
        ret.put("retMsg", "该订单不存在");
        return ret;
    }
    // 订单是否为当前用户当前企业
    if (!webuserInfo.getId().equals(bill.getUniqueId()) || !webenterprise.getId().equals(bill.getEnterprise())) {
        ret.put("retMsg", "您不能操作该订单");
        return ret;
    }
    // 判断是否是更新过了的订单,是的话直接从本地数据库获取证书的base64传递给页面
    if ((bill.getBillStatus() == ComNames.BILL_STATUS_8 || bill.getBillStatus() == ComNames.BILL_STATUS_7 || bill.getBillStatus() == ComNames.BILL_STATUS_6) && null != bill.getOldUserCert()) {
        // 根据订单号,找到订单更新后的证书信息
        CertBuf certBuf = sqlSession.selectOne("com.itrus.portal.db.CertBufMapper.selectNewCertBufByBillId", billId);
        // 证书更新信息发给浏览器,写入证书
        // 用户证书,Base64编码 (公钥证书),因为记录的时候,存的都是公钥证书,所以这个证书链也是个单证书而已
        ret.put("certChain", certBuf.getCertBuf());
        // 用户证书,Base64编码 (公钥证书)
        ret.put("certBase64", certBuf.getCertBuf());
        // 用户证书,Base64编码 (公钥证书)
        ret.put("certSignBuf", certBuf.getCertsignBuf());
        // KMC协议响应1
        ret.put("certKmcRep1", certBuf.getCertKmcRep1());
        // KMC协议响应2
        ret.put("certKmcRep2", certBuf.getCertKmcRep2());
        // //加密证书
        // 用户加密证书
        ret.put("encUserCert", certBuf.getEncUserCert());
        ret.put("status", 0);
        List<UserCert> userCert2 = userCertService.getUserCertByBill(bill.getId(), null);
        ret.put("certId", userCert2.get(0).getId());
        return ret;
    }
    String accountHash = "";
    // 根据订单ID从本地查找ra哈希值
    accountHash = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectRaHashByBillId", billId);
    if (!StringUtils.isNotBlank(accountHash)) {
        // 根据证书序列号查找RA哈希值
        try {
            accountHash = getRaInfo.getRaInfoByCertSerialNumber(certSn);
        } catch (UserInfoServiceException e) {
            ret.put("message", e.getMessage());
            return ret;
        }
    }
    // 查找raAccount
    RaAccountExample rae = new RaAccountExample();
    RaAccountExample.Criteria criteria = rae.or();
    criteria.andAccountHashEqualTo(accountHash);
    rae.setLimit(1);
    RaAccount raAccount = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByExample", rae);
    CertUtlis certUtlis = new CertUtlis();
    CertInfo certInfo = new CertInfo();
    UserCert oldUsercert = null;
    try {
        if (!bill.getBillStatus().equals(ComNames.BILL_STATUS_12)) {
            ret.put("message", "该订单下的证书未处于可更新状态");
            ret.put("status", 1007);
            return ret;
        }
        // 解密ra密码
        if (null != raAccount.getAaPassword()) {
            raAccount.setAaPassword(AESencrp.decrypt(raAccount.getAaPassword(), dbEncKey));
        }
        // 判断证书是否过期并且处于90天内的有效期
        oldUsercert = userCertService.getUserCertByCertSn(certSn);
        Date certEndTime = oldUsercert.getCertEndTime();
        logger.error("************过期时间********certEndTime" + certEndTime);
        int result = compareDate(certEndTime, new Date());
        logger.error("************过期状态********result" + result);
        // 用户证书剩余的天数
        Integer surplusDay = 0;
        surplusDay = differenceDate(certEndTime, new Date());
        Integer certValidity = null;
        // 判断订单中是否配了产品规格且有期限
        if (null != bill.getProductSpec() && 0 != bill.getProductSpec()) {
            ProductSpec productSpec = productSpecService.getProductSpec(bill.getProductSpec());
            Integer day = Integer.parseInt(productSpec.getProductValid());
            certValidity = 365 * day + 1 + (day / 4);
        }
        logger.error("产品规格期限************certValidity" + certValidity);
        if (result == 2) {
            logger.error("************证书过期更新********result=" + result);
            // 证书已经过期了,直接进行新证书申请
            if (null != certValidity) {
                logger.error("****给走申请证书接口的用户补充上剩余天数****certValidity=" + certValidity);
                // 给走申请证书接口的用户补充上剩余天数,因为用户指定的更新期限,可能跟原证书的年限不一致
                certValidity = certValidity + surplusDay;
                certInfo = renewUserService.applyCert(newCSR, productService.getProductById(bill.getProduct()), oldCertDn, certValidity);
            } else {
                logger.error("****证书更新方法****certSn=" + certSn);
                certInfo = certUtlis.renewAA(certSn, crt, raAccount.getAaPassword(), accountHash, raAccount.getAaPassword(), "", newCSR, pkcs7, raAccount);
            }
        // certInfo = renewUserService.applyCert(newCSR,
        // productService.getProductById(bill.getProduct()),
        // oldCertDn, certValidity);
        } else if (result == 3) {
            // 当证书过期,且超过90天
            ret.put("status", 1008);
            ret.put("message", "该证书已经过期超过了90天,无法更新");
            return ret;
        } else if (result == 1) {
            logger.error("****证书更新方法2****result=" + result);
            if (null != certValidity) {
                // 给走申请证书接口的用户补充上剩余天数,因为用户指定的更新期限,可能跟原证书的年限不一致
                certValidity = certValidity + surplusDay;
                certInfo = renewUserService.applyCert(newCSR, productService.getProductById(bill.getProduct()), oldCertDn, certValidity);
            } else {
                // 判断是否为passcord模式
                CaPasscode passcode = new CaPasscode();
                if (raAccount.getCertSignType() == 2) {
                    // 获取对应ra账号的passcode
                    RaAccountInfoExample raInfoExample = new RaAccountInfoExample();
                    RaAccountInfoExample.Criteria raInfoCriteria = raInfoExample.createCriteria();
                    raInfoCriteria.andHashValEqualTo(raAccount.getAccountHash());
                    raInfoExample.setOrderByClause("create_time desc");
                    raInfoExample.setLimit(1);
                    RaAccountInfo raAccountInfo = sqlSession.selectOne("com.itrus.portal.db.RaAccountInfoMapper.selectByExample", raInfoExample);
                    if (raAccountInfo == null) {
                        LogUtil.syslog(sqlSession, "制作证书", "不存在指定RA帐号");
                    }
                    // 获取对应passcode
                    try {
                        passcode = codeService.IssuedCode4Cert(raAccountInfo);
                        if (passcode == null) {
                            LogUtil.syslog(sqlSession, "制作证书", "没有有效授权码,请联系管理员");
                        }
                    } catch (TerminalServiceException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    // 进行证书更新,直接在原证书的基础上,签发一张新证书,需要有
                    certInfo = certUtlis.renewAA(certSn, crt, raAccount.getAaPassword(), accountHash, raAccount.getAaPassword(), passcode.getPasscode(), newCSR, pkcs7, raAccount);
                } else {
                    // 进行证书更新,直接在原证书的基础上,签发一张新证书,需要有
                    certInfo = certUtlis.renewAA(certSn, crt, raAccount.getAaPassword(), accountHash, raAccount.getAaPassword(), "", newCSR, pkcs7, raAccount);
                }
            }
        }
        UserCert userCert = updateUserCertAndCertBuf(certSn, certInfo, billId, raAccount.getId());
        UserLog userLog = new UserLog();
        userLog.setType("更新证书成功");
        userLog.setInfo("成功更新证书:" + certSn);
        userLog.setHostId("未知");
        userLog.setProject(bill.getProject());
        LogUtil.userlog(sqlSession, userLog);
        // 证书更新信息发给浏览器,写入证书
        // 用户证书PKCS7格式(含证书链)
        ret.put("certChain", certInfo.getCertSignBufP7());
        // 用户证书,Base64编码 (公钥证书)
        ret.put("certBase64", certInfo.getCertSignBuf());
        ret.put("certId", userCert.getId());
        // 用户证书,Base64编码 (公钥证书)
        ret.put("certSignBuf", certInfo.getCertSignBuf());
        // KMC协议响应1
        ret.put("certKmcRep1", certInfo.getCertKmcRep1());
        // KMC协议响应2
        ret.put("certKmcRep2", certInfo.getCertKmcRep2());
        // 加密证书
        // 用户加密证书
        ret.put("encUserCert", certInfo.getCertSignBufKmc());
        ret.put("status", 0);
        // 更新usercert和cerbuf
        return ret;
    } catch (MalformedURLException | RaServiceUnavailable_Exception e) {
        logger.error("更新证书:" + certSn + "出现异常,异常信息:" + e.getMessage());
        UserLog userLog = new UserLog();
        userLog.setType("更新证书失败");
        userLog.setInfo("url:updateCert,出错的证书:" + certSn + ",详细错误:" + e.getMessage());
        userLog.setHostId("未知");
        userLog.setProject(bill.getProject());
        LogUtil.userlog(sqlSession, userLog);
        ret.put("status", 1004);
        ret.put("message", "出现未知异常,请联系管理员处理");
        return ret;
    } catch (EncDecException e) {
        // TODO Auto-generated catch block
        logger.error("更新证书:" + certSn + "出现异常,异常信息:" + e.getMessage());
        UserLog userLog = new UserLog();
        userLog.setType("更新证书失败");
        userLog.setInfo("url:updateCert,出错的证书:" + certSn + ",详细错误:" + e.getMessage());
        userLog.setHostId("未知");
        userLog.setProject(bill.getProject());
        LogUtil.userlog(sqlSession, userLog);
        ret.put("status", 1005);
        ret.put("message", "出现未知异常,请联系管理员处理");
        return ret;
    } catch (Exception e) {
        if (StringUtils.isNotBlank(certInfo.getCertSerialNumber())) {
            // 新证书已签发,但未保存到数据库时 需打印新证书序列号
            logger.error("旧证书序列号:" + oldUsercert.getCertSn() + ",异常的新证书序列号:" + certInfo.getCertSerialNumber());
        }
        logger.error("更新证书:" + certSn + "出现异常,异常信息:" + e.getMessage());
        UserLog userLog = new UserLog();
        userLog.setType("更新证书失败");
        userLog.setInfo("url:updateCert,出错的证书:" + certSn + ",详细错误:" + e.getMessage());
        userLog.setHostId("未知");
        userLog.setProject(bill.getProject());
        LogUtil.userlog(sqlSession, userLog);
        ret.put("status", 1006);
        ret.put("message", "出现未知异常,请联系管理员处理");
        return ret;
    }
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) TerminalServiceException(com.itrus.portal.exception.TerminalServiceException) MalformedURLException(java.net.MalformedURLException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) HashMap(java.util.HashMap) EncDecException(com.itrus.portal.exception.EncDecException) UserInfoServiceException(com.itrus.portal.exception.UserInfoServiceException) Date(java.util.Date) MalformedURLException(java.net.MalformedURLException) TerminalServiceException(com.itrus.portal.exception.TerminalServiceException) CertificateException(java.security.cert.CertificateException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) SigningServerException(com.itrus.cryptorole.SigningServerException) UserInfoServiceException(com.itrus.portal.exception.UserInfoServiceException) EncDecException(com.itrus.portal.exception.EncDecException)

Example 4 with CertInfo

use of cn.topca.tca.ra.service.CertInfo in project portal by ixinportal.

the class MakeCertController method downloadPfxCert.

/**
 * 后台管理员下载pfx证书的接口
 *
 * @param id,订单id
 * @param request
 * @param response
 * @return
 */
@RequestMapping("/pfx/{id}")
public String downloadPfxCert(@PathVariable(value = "id") Long id, HttpServletRequest request, HttpServletResponse response) {
    Bill bill = billService.getBill(id);
    if (null == bill) {
        return null;
    }
    Integer uidIdx = 1;
    UserInfo webuserInfo = userInfoService.getUserInfoByBillId(id);
    Enterprise webenterprise = enterpriseService.getEnterpriseByBillId(id);
    boolean billFlag = webuserInfo.getId().equals(bill.getUniqueId()) && webenterprise.getId().equals(bill.getEnterprise());
    if (!billFlag) {
        return null;
    }
    // 用户已经下载过了,再次下载
    boolean downLoadFlag = bill.getBillStatus().equals(ComNames.BILL_STATUS_6) || bill.getBillStatus().equals(ComNames.BILL_STATUS_7) || bill.getBillStatus().equals(ComNames.BILL_STATUS_8);
    if (downLoadFlag) {
        // 根据订单号,找到订单对应的证书信息
        CertBuf certBuf = sqlSession.selectOne("com.itrus.portal.db.CertBufMapper.selectPfxCertByBillId", bill.getId());
        Date date = new Date();
        // 获取证书第一次下载时间和当前时间比较,如果超过了十五天,则不允许下载
        int day = DateUtils.daysOfTwo(date, certBuf.getCreateTime());
        if (day > 16) {
            return null;
        }
        // 从数据库中取出数据,返回给客户端.
        // 重置response对象中的缓冲区,该方法可以不写,但是你要保证response缓冲区没有其他数据,否则导出可能会出现问题,建议加上
        response.reset();
        String filename = webenterprise.getEnterpriseName() + "功能证书.pfx";
        filename = encodeFilename(filename, request);
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        response.setCharacterEncoding("utf-8");
        // 由于导出格式是pfx的文件,设置导出文件的响应头部信息
        response.setContentType("application/x-pkcs12");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            // 清理刷新缓冲区,将缓存中的数据将数据导出excel
            byte[] byteCert = Base64.decode(certBuf.getPfxCert());
            os.write(byteCert);
            os.flush();
            // 关闭os
            if (os != null) {
                os.close();
            }
            certBuf.setLastDownloadTime(new Date());
            certBuf.setCertDownloadNumber(certBuf.getCertDownloadNumber() + 1);
            downLoadCertService.updatePfxCert(certBuf);
            // 记录日志
            LogUtil.adminlog(sqlSession, "下载pfx证书", "企业名称:" + webenterprise.getEnterpriseName());
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LogUtil.adminlog(sqlSession, "下载pfx证书", "下载失败,错误信息:" + e.getMessage());
        }
    } else {
        // 用户未下载过,第一次下载
        if (bill.getBillStatus().equals(ComNames.BILL_STATUS_13)) {
            // 查询项目产品
            Product product = productService.getProduct(bill.getProduct());
            // 企业
            Enterprise enterprise = enterpriseService.getEnterpriseById(bill.getEnterprise());
            // 获取产品、RA配置
            RaAccount ra = raAccountService.getRaAccount(product.getRa());
            // 证书配置
            DigitalCert digitalcert = digitalCertService.getDigitalCert(product.getCert());
            // 下载证书
            String autoidType = "";
            Integer autoidValue = 0;
            String pfxCert = "";
            // 用户ID,用来最终匹配公钥证书和密钥对,一个用户id,只能使用一次,所以考虑使用订单号来作为用户id,避免一个用户只能下载一个证书.
            String userid = bill.getBillId() + (Math.random() * 1000 + 9000);
            // TODO
            String certPass = product.getPassword();
            // 20170410pfx私钥证书保护密码:需要根据产品配置的密码或获取
            // 产生CSR证书请求
            String certReqBuf = "";
            // 算法
            String algorithm = digitalCertService.getAlgorithm(digitalcert);
            // 下载证书
            CertInfo racertinfo = null;
            try {
                certReqBuf = GenUtil.GenP10(userid, "", algorithm);
                racertinfo = downLoadCertService.downLoadCert(product, ra, bill, digitalcert, uidIdx, certReqBuf, autoidType, autoidValue);
                pfxCert = GenUtil.GenPFX(userid, certPass, racertinfo.getCertSignBuf(), false, enterprise.getEnterpriseName());
                // 保存证书
                downLoadCertService.savePfxCertInfo(racertinfo, bill, ra.getId(), uidIdx, "", autoidType, autoidValue, pfxCert);
                // 从数据库中取出数据,返回给客户端.
                // 重置response对象中的缓冲区,该方法可以不写,但是你要保证response缓冲区没有其他数据,否则导出可能会出现问题,建议加上
                response.reset();
                String filename = webenterprise.getEnterpriseName() + "通讯证书.pfx";
                filename = encodeFilename(filename, request);
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
                response.setCharacterEncoding("utf-8");
                // 由于导出格式是pfx的文件,设置导出文件的响应头部信息
                response.setContentType("application/x-pkcs12");
                OutputStream os = null;
                os = response.getOutputStream();
                // 清理刷新缓冲区,将缓存中的数据将数据导出excel
                byte[] byteCert = Base64.decode(pfxCert);
                os.write(byteCert);
                os.flush();
                // 关闭os
                if (os != null) {
                    os.close();
                }
                // 记录日志
                LogUtil.adminlog(sqlSession, "下载pfx证书", "下载成功,企业名称:" + webenterprise.getEnterpriseName());
                return null;
            } catch (Exception e) {
                // TODO: handle exception
                LogUtil.adminlog(sqlSession, "下载pfx证书", "下载失败,错误信息:" + e.getMessage());
            }
        }
    }
    return null;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) OutputStream(java.io.OutputStream) Product(com.itrus.portal.db.Product) UserInfo(com.itrus.portal.db.UserInfo) IOException(java.io.IOException) Date(java.util.Date) EncDecException(com.itrus.portal.exception.EncDecException) IOException(java.io.IOException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) BigInteger(java.math.BigInteger) DigitalCert(com.itrus.portal.db.DigitalCert) RaAccount(com.itrus.portal.db.RaAccount) Bill(com.itrus.portal.db.Bill) Enterprise(com.itrus.portal.db.Enterprise) CertBuf(com.itrus.portal.db.CertBuf) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with CertInfo

use of cn.topca.tca.ra.service.CertInfo in project portal by ixinportal.

the class CertUtlis method enrollCertByWS.

// @Autowired
// private CaPasscodeService codeService;
public CertInfo enrollCertByWS(String csr, RaAccount raAccount, String uid) throws MalformedURLException, RaServiceUnavailable_Exception {
    String json = "{\"certValidity\":" + 60 + "}";
    CertInfo certInfo = null;
    UserAPIService service = new UserAPIService(new URL(raAccount.getServiceUrl()));
    UserAPIServicePortType client = service.getUserAPIServicePort();
    // 用户信息
    UserInfo userInfo = new UserInfo();
    userInfo.setUserEmail("test@itrus.com.cn");
    userInfo.setUserName("cceshi");
    userInfo.setUserOrgunit(raAccount.getAccountOrgUnit());
    userInfo.setUserOrganization(raAccount.getAccountOrganization());
    userInfo.setUserAdditionalField1("123");
    certInfo = client.enrollCertAA(userInfo, csr, raAccount.getAccountHash(), "itrusyes", "", json);
    return certInfo;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) UserAPIServicePortType(cn.topca.tca.ra.service.UserAPIServicePortType) UserInfo(cn.topca.tca.ra.service.UserInfo) UserAPIService(cn.topca.tca.ra.service.UserAPIService) URL(java.net.URL)

Aggregations

CertInfo (cn.topca.tca.ra.service.CertInfo)20 JSONObject (com.alibaba.fastjson.JSONObject)11 UserInfo (cn.topca.tca.ra.service.UserInfo)10 HashMap (java.util.HashMap)9 RaServiceUnavailable_Exception (cn.topca.tca.ra.service.RaServiceUnavailable_Exception)8 RaAccount (com.itrus.portal.db.RaAccount)8 Date (java.util.Date)8 SimpleDateFormat (java.text.SimpleDateFormat)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 DigitalCert (com.itrus.portal.db.DigitalCert)6 ParseException (java.text.ParseException)6 Bill (com.itrus.portal.db.Bill)5 Product (com.itrus.portal.db.Product)5 IOException (java.io.IOException)5 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)5 UserAPIService (cn.topca.tca.ra.service.UserAPIService)4 UserAPIServicePortType (cn.topca.tca.ra.service.UserAPIServicePortType)4 JSONArray (com.alibaba.fastjson.JSONArray)4 CertBuf (com.itrus.portal.db.CertBuf)4 Enterprise (com.itrus.portal.db.Enterprise)4