Search in sources :

Example 11 with CertInfo

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

the class DownLoadCertWebController method downLoadCert.

@RequestMapping("/{id}")
@ResponseBody
public Map<String, Object> downLoadCert(@PathVariable(value = "id") Long id, @RequestParam(value = "uidIdx", required = true) Integer uidIdx, @RequestParam(value = "csr", required = true) String csr, @RequestParam(value = "keySn", required = false) String keySn, HttpSession session) {
    Map<String, Object> retMap = new HashMap<String, Object>();
    retMap.put("retCode", 0);
    UserInfo webuserInfo = (UserInfo) session.getAttribute("webuserInfo");
    Enterprise webenterprise = (Enterprise) session.getAttribute("webenterprise");
    if (null == webuserInfo || null == webenterprise) {
        // 2标识登录已经失效,需跳转到登录页面
        retMap.put("retCode", 2);
        retMap.put("retMsg", "登录状态失效");
        return retMap;
    }
    Bill bill = billService.getBill(id);
    if (null == bill) {
        retMap.put("retMsg", "该订单不存在");
        return retMap;
    }
    // 订单是否为当前用户当前企业
    if (!webuserInfo.getId().equals(bill.getUniqueId()) || !webenterprise.getId().equals(bill.getEnterprise())) {
        retMap.put("retMsg", "您不能操作该订单");
        return retMap;
    }
    // 判断该订单状态是否为待下载,是否已经关联了证书
    List<String> certStatus = new ArrayList<String>();
    certStatus.add(ComNames.CERT_STATUS_1);
    certStatus.add(ComNames.CERT_STATUS_2);
    List<UserCert> userCerts = userCertService.getUserCertByBill(bill.getId(), certStatus);
    if (!bill.getBillStatus().equals(ComNames.BILL_STATUS_13) || !userCerts.isEmpty()) {
        retMap.put("retMsg", "该证书状态为已下载或订单还未审核");
        return retMap;
    }
    Product product = productService.getProduct(bill.getProduct());
    DigitalCert digitalCert = digitalCertService.getDigitalCert(product.getCert());
    RaAccount ra = raAccountService.getRaAccount(product.getRa());
    // 下载证书
    String autoidType = "";
    Integer autoidValue = 0;
    try {
        // 下载证书
        CertInfo racertinfo = downLoadCertService.downLoadCert(product, ra, bill, digitalCert, uidIdx, csr, autoidType, autoidValue);
        // 保存证书
        downLoadCertService.saveCertInfo(racertinfo, bill, ra.getId(), uidIdx, keySn, autoidType, autoidValue);
        // 返回数字证书
        retMap.put("retCode", 1);
        retMap.put("certChain", racertinfo.getCertSignBufP7());
        retMap.put("certSn", racertinfo.getCertSerialNumber());
        retMap.put("certSignBuf", racertinfo.getCertSignBuf());
        retMap.put("certKmcRep1", racertinfo.getCertKmcRep1());
        retMap.put("certKmcRep2", racertinfo.getCertKmcRep2());
        // 加密证书
        retMap.put("encUserCert", racertinfo.getCertSignBufKmc());
        // 记录日志
        UserLog userlog = new UserLog();
        userlog.setProject(webuserInfo.getProject());
        userlog.setType("用户下载证书");
        userlog.setInfo(webenterprise.getEnterpriseName() + "下载证书成功");
        userlog.setHostId("未知");
        userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
        LogUtil.userlog(sqlSession, userlog);
    } catch (Exception e) {
        e.printStackTrace();
        retMap.put("retMsg", e.getMessage());
        // 记录日志
        UserLog userlog = new UserLog();
        userlog.setProject(webuserInfo.getProject());
        userlog.setType("用户下载证书");
        userlog.setInfo("url:downLoadCert,详细错误:" + e.getMessage());
        userlog.setHostId("未知");
        userlog.setSn(null == webuserInfo.getUniqueId() ? null : webuserInfo.getUniqueId());
        LogUtil.userlog(sqlSession, userlog);
        return retMap;
    }
    return retMap;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Product(com.itrus.portal.db.Product) UserInfo(com.itrus.portal.db.UserInfo) UserLog(com.itrus.portal.db.UserLog) 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) JSONObject(com.alibaba.fastjson.JSONObject) UserCert(com.itrus.portal.db.UserCert) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 12 with CertInfo

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

the class APIService method lookup.

/**
 * 证书查询接口
 * @param authHmac
 * @param appId
 * @param billId
 * @param request
 * @return
 */
@PostMapping(value = "/cert/search")
@ResponseBody
public Map<String, Object> lookup(@RequestHeader("Content-Signature") String authHmac, @RequestParam(value = "appId", required = true) String appId, @RequestParam(value = "billId", required = true) String billId, HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("status", 0);
    log.error("appId=" + appId + "billId=" + billId);
    // 验证参数是否完整
    if (StringUtils.isEmpty(authHmac) || StringUtils.isEmpty(appId) || StringUtils.isEmpty(billId)) {
        result.put("status", 0);
        result.put("message", "提交的参数信息不完整");
        return result;
    }
    // 得到应用信息 改成service
    Map<String, ApplicationInfo> appInfoMap = CacheCustomer.getAPP_INFO_MAP();
    ApplicationInfo applicationInfo = appInfoMap.get(appId);
    if (applicationInfo == null) {
        ApplicationInfoExample applicationInfoExample = new ApplicationInfoExample();
        ApplicationInfoExample.Criteria appInfoExampleCriteria = applicationInfoExample.createCriteria();
        appInfoExampleCriteria.andAppIdEqualTo(appId);
        applicationInfo = sqlSession.selectOne("com.itrus.portal.db.ApplicationInfoMapper.selectByExample", applicationInfoExample);
    }
    if (applicationInfo == null) {
        result.put("message", "应用标识不存在");
        return result;
    }
    if (!applicationInfo.getAccessIp().contains(request.getRemoteAddr()) && "1".equals(applicationInfo.getIsIpStatus())) {
        result.put("status", -1);
        result.put("message", "没有此服务权限");
        log.error("APIService_AccsessIp : " + request.getRemoteAddr());
        return result;
    }
    // 验证hmac有效性
    try {
        String macVal = CertService.hmacSha1(applicationInfo.getSecretKey().getBytes(), (appId + billId).getBytes("utf-8"));
        if (!authHmac.equals("HMAC-SHA1 " + macVal)) {
            result.put("status", -2);
            result.put("message", "服务密钥错误");
            return result;
        }
    } catch (Exception e) {
        result.put("status", -3);
        result.put("message", "Hmac验证错误");
        e.printStackTrace();
        return result;
    }
    BillExample billExample = new BillExample();
    BillExample.Criteria criteria = billExample.or();
    criteria.andBillIdEqualTo(billId);
    Bill bill = sqlSession.selectOne("com.itrus.portal.db.BillMapper.selectByExample", billExample);
    if (bill == null) {
        result.put("message", "没有此订单");
        return result;
    }
    Product product = productService.getProduct(bill.getProduct());
    DigitalCert dcert = sqlSession.selectOne("com.itrus.portal.db.DigitalCertMapper.selectByPrimaryKey", product.getCert());
    List<String> listcert = new ArrayList<String>();
    if ("3".equals(dcert.getCertType())) {
        Integer uidIdx = 1;
        // 用户已经下载过了,再次下载
        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());
            listcert.add(certBuf.getPfxCert());
            result.put("status", 1);
            result.put("pfxData", listcert);
        } 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);
                    listcert.add(pfxCert);
                    result.put("status", 1);
                    result.put("pfxData", listcert);
                } catch (Exception e) {
                    result.put("status", -1);
                    result.put("message", "pfx证书下载错误" + e.getMessage());
                }
            }
        }
    } else {
        List<UserCert> certlist = userCertService.getUserCertByBill(bill.getId(), null);
        for (UserCert uc : certlist) {
            CertBuf cb = sqlSession.selectOne("com.itrus.portal.db.CertBufMapper.selectByPrimaryKey", uc.getCertBuf());
            listcert.add(cb.getCertBuf());
        }
        if (listcert.size() > 0) {
            result.put("status", 1);
            result.put("cerData", listcert);
        } else {
            result.put("message", "没有查找到相应证书");
        }
    }
    return result;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) ApplicationInfoExample(com.itrus.portal.db.ApplicationInfoExample) HashMap(java.util.HashMap) ApplicationInfo(com.itrus.portal.db.ApplicationInfo) ArrayList(java.util.ArrayList) Product(com.itrus.portal.db.Product) JSONException(org.json.JSONException) UserInfoServiceException(com.itrus.portal.exception.UserInfoServiceException) DigitalCert(com.itrus.portal.db.DigitalCert) BillExample(com.itrus.portal.db.BillExample) RaAccount(com.itrus.portal.db.RaAccount) Bill(com.itrus.portal.db.Bill) CertBuf(com.itrus.portal.db.CertBuf) Enterprise(com.itrus.portal.db.Enterprise) UserinfoEnterprise(com.itrus.portal.db.UserinfoEnterprise) JSONObject(com.alibaba.fastjson.JSONObject) UserCert(com.itrus.portal.db.UserCert) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 13 with CertInfo

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

the class CertService method make.

/**
 * 制证
 *
 * @param authHmac hmac签名值,采用HmacSHA1算法
 * @param csr      证书请求CSR
 * @param billId   订单号
 * @param uid      用户id
 * @param userId   Msign的userID
 * @return status:message 1:制作证书成功 0:提交的参数信息不完整
 *         data:{userId:Msign的userID,buf:证书buf,bufP7:证书bufP7,certDn:证书DN,certSn:证书SN,issuerDn:颁发者DN,
 *               startTime:证书有效期开始日期,endTime:证书有效期结束日期}
 */
@RequestMapping(value = "/make")
@ResponseBody
public Map<String, Object> make(@RequestHeader("authHmac") String authHmac, @RequestParam("csr") String csr, @RequestParam("billId") String billId, @RequestParam(value = "uid", required = false) String uid, @RequestParam(value = "userId", required = false) String userId, @RequestParam(value = "delayDays", required = false) Integer delayDays) {
    Map<String, Object> result = new HashMap<String, Object>(4);
    // 验证参数是否完整
    if (StringUtils.isBlank(authHmac) || StringUtils.isBlank(csr) || StringUtils.isBlank(billId)) {
        result.put("status", 0);
        result.put("message", "提交的参数信息不完整");
        return result;
    }
    LogUtil.syslog(sqlSession, "调用接口", "调用制证接口");
    // 查询订单
    BillExample be = new BillExample();
    BillExample.Criteria bc = be.createCriteria();
    bc.andBillIdEqualTo(billId);
    // bc.andMcstatusNotEqualTo(1);
    Bill bill = sqlSession.selectOne("com.itrus.portal.db.BillMapper.selectByExample", be);
    // log.error(bill.getMcstatus()+"--------------输出日志---------------"+bill);
    if (null == bill) {
        // log.error(bill.getMcstatus()+"---------------------------------------------"+bill);
        // System.out.println(bill.getMcstatus()+"=******************************="+bill);
        result.put("status", -1);
        result.put("message", "该订单不存在");
        return result;
    }
    if (bill.getIsenterprisecert() != null && !bill.getIsenterprisecert()) {
        result.put("status", -6);
        result.put("message", "未提交自动制证订单");
        return result;
    }
    // 查询项目产品
    Product product = sqlSession.selectOne("com.itrus.portal.db.ProductMapper.selectByPrimaryKey", bill.getProduct());
    SignatureConfig sc = sqlSession.selectOne("com.itrus.portal.db.SignatureConfigMapper.selectByPrimaryKey", product.getSignature());
    // 验证hmac有效性
    /*try {
			String macVal = hmacSha1(sc.getAddressKey().getBytes(),(csr+billId+uid+userId).getBytes("utf-8"));
					//Base64.encode(HMACSHA1.getHmacSHA1(csr+billId+uid+userId, sc.getAddressKey()), false);
			if (!authHmac.equals(macVal)) {
				result.put("status", -2);
				result.put("message", "服务密钥错误");
				return result;
			}
		} catch (Exception e) {
			result.put("status", -3);
			result.put("message", "Hmac验证错误");
			e.printStackTrace();
			return result;
		}*/
    // 证书配置
    DigitalCert digitalcert = sqlSession.selectOne("com.itrus.portal.db.DigitalCertMapper.selectByPrimaryKey", product.getCert());
    JSONArray certinfo = null;
    if ("3".equals(digitalcert.getInitBuy())) {
        // 解析项目产品中,certinfo配置信息
        certinfo = JSONArray.parseArray(product.getCertinfos());
    } else {
        // 解析项目产品中,certinfo配置信息
        certinfo = JSONArray.parseArray(product.getCertinfo());
    }
    // 解析订单中uid信息
    JSONObject uiddata = JSONObject.parseObject(bill.getUid());
    // 获取产品、RA配置
    RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", product.getRa());
    CertUtlis certutil = new CertUtlis();
    // 组织RA参数
    UserInfo rauserinfo = new UserInfo();
    UIDInfoUtils uidutils = new UIDInfoUtils();
    uidutils.initService(businessService, orgCodeService, taxCertService, identityCardService, userInfoService, enterpriseService);
    String autoidType = "";
    Integer autoidValue = 0;
    for (int i = 0; i < certinfo.size(); i++) {
        JSONObject obj = certinfo.getJSONObject(i);
        String raParaName = obj.getString("raParaName");
        if (raParaName == null)
            continue;
        String autoid = obj.getString("autoid");
        String constValue = obj.getString("constValue");
        String refName = obj.getString("refName");
        String val = null;
        if (constValue != null) {
            val = constValue;
        } else if (refName != null) {
            if (refName.indexOf("?") == -1)
                val = uidutils.getUidInfo(bill.getId(), refName);
            else {
                val = "";
                String[] arr = refName.split("\\?", 2);
                if (arr.length == 2) {
                    String condition = arr[0].trim();
                    String[] refarr = arr[1].split(":", 2);
                    if (refarr.length == 2) {
                        boolean bret = uidutils.checkCondition(bill.getId(), condition);
                        if (bret)
                            val = uidutils.getUidInfo(bill.getId(), refarr[0].trim());
                        else
                            val = uidutils.getUidInfo(bill.getId(), refarr[1].trim());
                    }
                }
            }
        } else if (autoid != null) {
            String autoidPrev = obj.getString("autoidPrev");
            autoidType = obj.getString("autoidType");
            // + "_" + uidIdx.toString());
            String uidval = uiddata.getString(obj.getString("inputName"));
            val = uidval;
            if (org.apache.commons.lang.StringUtils.isNotBlank(uidval) && uidval.indexOf(autoidPrev) == 0) {
                String autoidPrevDate = obj.getString("autoidPrevDate");
                try {
                    if (autoidPrevDate == null || autoidPrevDate.length() == 0)
                        autoidValue = Integer.parseInt(uidval.substring(autoidPrev.length()));
                    else
                        autoidValue = Integer.parseInt(uidval.substring(autoidPrev.length() + autoidPrevDate.length()));
                } catch (Exception e) {
                    e.printStackTrace();
                    autoidValue = 0;
                }
            }
        } else {
            // + "_" + uidIdx.toString());
            val = uiddata.getString(obj.getString("inputName"));
        }
        certutil.setUserInfoVal(rauserinfo, raParaName, val);
    }
    // 证书有效期
    // {"0":"1年","1":"2年","2":"3年","3":"5年","4":"10年"})
    Integer certValidity = 7;
    if ("0".compareTo(digitalcert.getCertDeadline()) == 0) {
        certValidity = 365 * 1 + 1;
    } else if ("1".compareTo(digitalcert.getCertDeadline()) == 0) {
        certValidity = 365 * 2 + 1;
    } else if ("2".compareTo(digitalcert.getCertDeadline()) == 0) {
        certValidity = 365 * 3 + 1;
    } else if ("3".compareTo(digitalcert.getCertDeadline()) == 0) {
        certValidity = 365 * 5 + 2;
    } else if ("4".compareTo(digitalcert.getCertDeadline()) == 0) {
        certValidity = 365 * 10 + 2;
    }
    if (null != delayDays) {
        certValidity += delayDays;
    }
    // 判断是否为passcord模式
    // CaPasscode passcode = new CaPasscode();
    // if (ra.getCertSignType() == 2) {
    // // 获取对应ra账号的passcode
    // RaAccountInfoExample raInfoExample = new RaAccountInfoExample();
    // RaAccountInfoExample.Criteria raInfoCriteria = raInfoExample.createCriteria();
    // raInfoCriteria.andHashValEqualTo(ra.getAccountHash());
    // raInfoExample.setOrderByClause("create_time desc");
    // raInfoExample.setLimit(1);
    // RaAccountInfo raAccountInfo = sqlSession.selectOne("com.itrus.ukey.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();
    // }
    // }
    // 调用RA
    CertInfo racertinfo = null;
    try {
        if (ra.getAaPassword() != null)
            log.error("********************************************************");
        ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
        racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
        log.error("-----------------------------------------------------");
    } catch (RaServiceUnavailable_Exception e) {
        e.printStackTrace();
        result.put("status", -4);
        result.put("message", e.getMessage());
        // 记录日志
        log.error("*************12323232323232323232323232323232323");
        String oper = "制作证书失败";
        String info = "企业名称: " + uidutils.getUidInfo(bill.getId(), "enterprise.enterpriseName") + ",异常信息: " + e.toString();
        LogUtil.adminlog(sqlSession, oper, info);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        result.put("status", -5);
        result.put("message", e.getMessage());
        // 记录日志
        log.error("********7sdfsdgfdgdfghfhfgjhghjfghgsdfsdgdhfhdfd*************");
        String oper = "制作证书失败";
        String info = "企业名称: " + uidutils.getUidInfo(bill.getId(), "enterprise.enterpriseName") + ",异常信息: " + e.toString();
        LogUtil.adminlog(sqlSession, oper, info);
        return result;
    }
    // 解析数字证书信息
    // 存储数字证书信息
    CertBuf certbuf = new CertBuf();
    certbuf.setCreateTime(new Date());
    certbuf.setCertBuf(racertinfo.getCertSignBuf());
    sqlSession.insert("com.itrus.portal.db.CertBufMapper.insert", certbuf);
    UserCert usercert = new UserCert();
    usercert.setBill(bill.getId());
    usercert.setRaAccount(ra.getId());
    usercert.setCertBuf(certbuf.getId());
    // usercert.setUidIdx(uidIdx);
    usercert.setCertDn(racertinfo.getCertSubjectDn());
    usercert.setCertSn(racertinfo.getCertSerialNumber());
    usercert.setIssuerDn(racertinfo.getCertIssuerDn());
    usercert.setCertStatus("1");
    usercert.setCertUid("certUid");
    usercert.setCertSource(ComNames.CERT_SOURCE_2);
    usercert.setProduct(product.getId());
    // usercert.setKeySn(keySn);
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        usercert.setCertStartTime(sdf.parse(racertinfo.getCertNotBefore()));
        usercert.setCertEndTime(sdf.parse(racertinfo.getCertNotAfter()));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    usercert.setSha1Fingerprint("setSha1Fingerprint");
    // autoid 数据
    if (!autoidType.equals("")) {
        usercert.setAutoidType(autoidType);
        usercert.setAutoidValue(autoidValue);
    }
    usercert.setEnterprise(bill.getEnterprise());
    try {
        sqlSession.insert("com.itrus.portal.db.UserCertMapper.insert", usercert);
        sqlSession.flushStatements();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 查询userCert中,该bill的记录数目,如果数据 大于等于 bill 里面的购买数量,则修改该bill为制证完成
    List<Map> usercertall = sqlSession.selectList("com.itrus.portal.db.UserCertMapper.selectByPrimaryBillKey", bill.getId());
    if (bill.getIsenterprisecert() != null && bill.getIsenterprisecert()) {
        // 判断是否需要友互通自动制证
        if (bill.getIscertinfo() != null && bill.getIscertinfo() == 3) {
            // 判断是否已管理员制证
            bill.setBillStatus(6);
            if (null == bill.getDelivery()) {
                bill.setBillStatus(8);
            } else {
                LogUtil.syslog(sqlSession, "制作证书", "错误:bill.getDelivery()" + bill.getDelivery());
            }
            sqlSession.update("com.itrus.portal.db.BillMapper.updateByPrimaryKey", bill);
            sqlSession.flushStatements();
        }
        // 友互通自动制证已制证
        bill.setIscertinfo(1);
        sqlSession.update("com.itrus.portal.db.BillMapper.updateByPrimaryKey", bill);
        sqlSession.flushStatements();
    } else {
        // bill.setIscertinfo(2);//友互通自动制证未制证
        if (usercertall.size() >= bill.getProductNum()) {
            bill.setBillStatus(6);
            if (null == bill.getDelivery()) {
                bill.setBillStatus(8);
            } else {
                LogUtil.syslog(sqlSession, "制作证书", "错误:bill.getDelivery()" + bill.getDelivery());
            }
            sqlSession.update("com.itrus.portal.db.BillMapper.updateByPrimaryKey", bill);
            sqlSession.flushStatements();
        } else {
            LogUtil.syslog(sqlSession, "制作证书", "错误:usercertall.size()" + usercertall.size() + "bill.getProductNum()" + bill.getProductNum());
        }
    }
    // 记录日志
    String oper = "制作证书";
    String info = "数字证书: " + racertinfo.getCertSerialNumber() + ", " + racertinfo.getCertSubjectDn();
    LogUtil.syslog(sqlSession, oper, info);
    result.put("status", 1);
    result.put("message", "制作证书成功");
    Map<String, Object> data = new HashMap<String, Object>(8);
    data.put("userId", userId);
    data.put("buf", racertinfo.getCertSignBuf());
    data.put("bufP7", racertinfo.getCertSignBufP7());
    data.put("certDn", racertinfo.getCertSubjectDn());
    data.put("certSn", racertinfo.getCertSerialNumber());
    data.put("issuerDn", racertinfo.getCertIssuerDn());
    data.put("startTime", usercert.getCertStartTime());
    data.put("endTime", usercert.getCertEndTime());
    result.put("data", data);
    return result;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) HashMap(java.util.HashMap) UserInfo(cn.topca.tca.ra.service.UserInfo) JSONArray(com.alibaba.fastjson.JSONArray) ParseException(java.text.ParseException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) Map(java.util.Map) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 14 with CertInfo

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

the class MakeCertController method makecert.

// 制作证书
@RequestMapping(value = "/make/{id}", produces = "text/html")
@ResponseBody
public Map<String, Object> makecert(@RequestParam(value = "uidIdx", required = true) Integer uidIdx, @RequestParam(value = "csr", required = true) String csr, @RequestParam(value = "pid", required = true) Long pid, @RequestParam(value = "index", required = false) Integer index, @RequestParam(value = "keySn", required = false) String keySn, @PathVariable("id") Long id) {
    Map<String, Object> ret = new HashMap<String, Object>();
    // 查询订单
    Bill bill = sqlSession.selectOne("com.itrus.portal.db.BillMapper.selectByPrimaryKey", id);
    // 查询项目产品
    Product product = sqlSession.selectOne("com.itrus.portal.db.ProductMapper.selectByPrimaryKey", pid);
    // 解析项目产品中,certinfo配置信息
    JSONArray certinfo = JSONArray.parseArray(product.getCertinfo());
    // 解析订单中uid信息{"ADDTIONAL_FIELD1_1":"","ADDTIONAL_FIELD3_1":"","ADDTIONAL_FIELD4_1":"G2016071301","inputName":"inputValue"}
    JSONObject uid = JSONObject.parseObject(bill.getUid());
    if (null != index) {
        if (index == 1) {
            uid = JSONObject.parseObject(bill.getUid1());
        }
        if (index == 2) {
            uid = JSONObject.parseObject(bill.getUid2());
        }
        if (index == 3) {
            uid = JSONObject.parseObject(bill.getUid3());
        }
    }
    // 获取产品、RA配置
    RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", product.getRa());
    com.itrus.portal.utils.CertUtlis certutil = new com.itrus.portal.utils.CertUtlis();
    // 证书配置
    DigitalCert digitalcert = sqlSession.selectOne("com.itrus.portal.db.DigitalCertMapper.selectByPrimaryKey", product.getCert());
    // 组织RA参数
    cn.topca.tca.ra.service.UserInfo rauserinfo = new cn.topca.tca.ra.service.UserInfo();
    UIDInfoUtils uidutils = new UIDInfoUtils();
    uidutils.initService(businessService, orgCodeService, taxCertService, identityCardService, userInfoService, enterpriseService);
    String autoidType = "";
    Integer autoidValue = 0;
    for (int i = 0; i < certinfo.size(); i++) {
        JSONObject obj = certinfo.getJSONObject(i);
        String raParaName = obj.getString("raParaName");
        if (raParaName == null)
            continue;
        // "autoid":"yes",
        String autoid = obj.getString("autoid");
        // "raParaName": "userName",
        String constValue = obj.getString("constValue");
        // "constValue": "test@itrus.com.cn"
        String refName = obj.getString("refName");
        String val = null;
        if (constValue != null) {
            val = constValue;
        } else if (refName != null) {
            if (refName.indexOf("?") == -1)
                val = uidutils.getUidInfo(bill.getId(), refName);
            else {
                val = "";
                String[] arr = refName.split("\\?", 2);
                if (arr.length == 2) {
                    String condition = arr[0].trim();
                    String[] refarr = arr[1].split(":", 2);
                    if (refarr.length == 2) {
                        boolean bret = uidutils.checkCondition(bill.getId(), condition);
                        if (bret)
                            val = uidutils.getUidInfo(bill.getId(), refarr[0].trim());
                        else
                            val = uidutils.getUidInfo(bill.getId(), refarr[1].trim());
                    }
                }
            }
        } else if (autoid != null) {
            // "autoidPrev":"G",
            String autoidPrev = obj.getString("autoidPrev");
            // "autoidType":"mytestautoid",
            autoidType = obj.getString("autoidType");
            // "inputName": "ADDTIONAL_FIELD4",存在多个值
            String uidval = uid.getString(obj.getString("inputName") + "_" + uidIdx.toString());
            val = uidval;
            if (StringUtils.isNotBlank(uidval) && uidval.indexOf(autoidPrev) == 0) {
                // "autoidPrevDate":"yyyyMMdd",
                String autoidPrevDate = obj.getString("autoidPrevDate");
                try {
                    if (autoidPrevDate == null || autoidPrevDate.length() == 0)
                        autoidValue = Integer.parseInt(uidval.substring(autoidPrev.length()));
                    else
                        autoidValue = Integer.parseInt(uidval.substring(autoidPrev.length() + autoidPrevDate.length()));
                } catch (Exception e) {
                    e.printStackTrace();
                    autoidValue = 0;
                }
            }
        } else {
            val = uid.getString(obj.getString("inputName") + "_" + uidIdx.toString());
        }
        certutil.setUserInfoVal(rauserinfo, raParaName, val);
    }
    // 证书有效期
    // {"0":"1年","1":"2年","2":"3年","3":"5年","4":"10年"})
    Integer certValidity = 5;
    boolean hasProductSpec = false;
    // 判断订单中是否配了产品规格且有期限
    ProductSpec productSpec = null;
    if (null != bill.getProductSpec() && 0 != bill.getProductSpec()) {
        productSpec = productSpecService.getProductSpec(bill.getProductSpec());
        if (StringUtils.isNotBlank(productSpec.getProductValid())) {
            hasProductSpec = true;
        }
    }
    if (null != index) {
        if (index == 1)
            if (null != bill.getProductSpec1() && 0 != bill.getProductSpec1()) {
                productSpec = productSpecService.getProductSpec(bill.getProductSpec1());
                if (StringUtils.isNotBlank(productSpec.getProductValid())) {
                    hasProductSpec = true;
                }
            }
        if (index == 2)
            if (null != bill.getProductSpec2() && 0 != bill.getProductSpec2()) {
                productSpec = productSpecService.getProductSpec(bill.getProductSpec2());
                if (StringUtils.isNotBlank(productSpec.getProductValid())) {
                    hasProductSpec = true;
                }
            }
        if (index == 3)
            if (null != bill.getProductSpec3() && 0 != bill.getProductSpec3()) {
                productSpec = productSpecService.getProductSpec(bill.getProductSpec3());
                if (StringUtils.isNotBlank(productSpec.getProductValid())) {
                    hasProductSpec = true;
                }
            }
    }
    if (hasProductSpec) {
        Integer day = Integer.parseInt(productSpec.getProductValid());
        if (day == 100) {
            // TODO 测试时候,配置年限为100年,则有效期为10天
            certValidity = 1;
        } else {
            certValidity = 365 * day + 1 + (day / 4);
        }
    } else {
        if ("0".compareTo(digitalcert.getCertDeadline()) == 0) {
            certValidity = 365 * 1 + 1;
        } else if ("1".compareTo(digitalcert.getCertDeadline()) == 0) {
            certValidity = 365 * 2 + 1;
        } else if ("2".compareTo(digitalcert.getCertDeadline()) == 0) {
            certValidity = 365 * 3 + 1;
        } else if ("3".compareTo(digitalcert.getCertDeadline()) == 0) {
            certValidity = 365 * 5 + 2;
        } else if ("4".compareTo(digitalcert.getCertDeadline()) == 0) {
            certValidity = 365 * 10 + 2;
        } else if ("-1".compareTo(digitalcert.getCertDeadline()) == 0) {
            // 数字证书没有配置年限(-1),默认10天有效期
            certValidity = 10;
        }
    }
    log.error("证书期限*********" + certValidity);
    // 调用RA
    CertInfo racertinfo = null;
    try {
        if (ra.getAaPassword() != null)
            ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
        racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
    } catch (RaServiceUnavailable_Exception e) {
        e.printStackTrace();
        ret.put("status", 1001);
        ret.put("message", e.getMessage());
        // 记录日志
        String oper = "制作证书失败";
        String info = "企业名称: " + uidutils.getUidInfo(bill.getId(), "enterprise.enterpriseName") + ",参数:" + ToStringBuilder.reflectionToString(rauserinfo) + ",异常信息: " + e.toString();
        LogUtil.adminlog(sqlSession, oper, info);
        return ret;
    } catch (Exception e) {
        e.printStackTrace();
        ret.put("status", 1002);
        ret.put("message", e.getMessage());
        // 记录日志
        String oper = "制作证书失败";
        String info = "企业名称: " + uidutils.getUidInfo(bill.getId(), "enterprise.enterpriseName") + "参数:" + ToStringBuilder.reflectionToString(rauserinfo) + ",异常信息: " + e.toString();
        LogUtil.adminlog(sqlSession, oper, info);
        return ret;
    }
    // 解析数字证书信息
    // 存储数字证书信息
    CertBuf certbuf = new CertBuf();
    certbuf.setCreateTime(new Date());
    certbuf.setCertBuf(racertinfo.getCertSignBuf());
    certbuf.setCertKmcRep1(racertinfo.getCertKmcRep1());
    certbuf.setCertKmcRep2(racertinfo.getCertKmcRep2());
    certbuf.setCertsignBuf(racertinfo.getCertSignBuf());
    certbuf.setEncUserCert(racertinfo.getCertSignBufKmc());
    sqlSession.insert("com.itrus.portal.db.CertBufMapper.insert", certbuf);
    UserCert usercert = new UserCert();
    usercert.setBill(bill.getId());
    usercert.setRaAccount(ra.getId());
    usercert.setCertBuf(certbuf.getId());
    usercert.setUidIdx(uidIdx);
    usercert.setCertDn(racertinfo.getCertSubjectDn());
    usercert.setCertSn(racertinfo.getCertSerialNumber());
    usercert.setIssuerDn(racertinfo.getCertIssuerDn());
    usercert.setCertStatus("1");
    usercert.setCertUid("certUid");
    usercert.setProduct(pid);
    if (StringUtils.isNotBlank(keySn))
        // 设置证书keySn
        usercert.setKeySn(keySn);
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        usercert.setCertStartTime(sdf.parse(racertinfo.getCertNotBefore()));
        usercert.setCertEndTime(sdf.parse(racertinfo.getCertNotAfter()));
    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }
    usercert.setSha1Fingerprint("setSha1Fingerprint");
    // autoid 数据
    if (!autoidType.equals("")) {
        usercert.setAutoidType(autoidType);
        usercert.setAutoidValue(autoidValue);
    }
    usercert.setEnterprise(bill.getEnterprise());
    try {
        sqlSession.insert("com.itrus.portal.db.UserCertMapper.insert", usercert);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 查询userCert中,该bill的记录数目,如果数据 大于等于 bill 里面的购买数量,则修改该bill为制证完成
    updateBillStatus(bill, product);
    // 记录日志
    String oper = "制作证书";
    String info = "数字证书: " + racertinfo.getCertSerialNumber() + ", " + racertinfo.getCertSubjectDn();
    LogUtil.adminlog(sqlSession, oper, info);
    // 返回数字证书
    ret.put("certChain", racertinfo.getCertSignBufP7());
    ret.put("certsignBuf", racertinfo.getCertSignBuf());
    ret.put("certKmcRep1", racertinfo.getCertKmcRep1());
    ret.put("certKmcRep2", racertinfo.getCertKmcRep2());
    // 加密证书
    ret.put("encUserCert", racertinfo.getCertSignBufKmc());
    ret.put("status", 0);
    return ret;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) HashMap(java.util.HashMap) Product(com.itrus.portal.db.Product) UserInfo(com.itrus.portal.db.UserInfo) UIDInfoUtils(com.itrus.portal.utils.UIDInfoUtils) DigitalCert(com.itrus.portal.db.DigitalCert) RaAccount(com.itrus.portal.db.RaAccount) CertBuf(com.itrus.portal.db.CertBuf) UserCert(com.itrus.portal.db.UserCert) JSONArray(com.alibaba.fastjson.JSONArray) ProductSpec(com.itrus.portal.db.ProductSpec) EncDecException(com.itrus.portal.exception.EncDecException) IOException(java.io.IOException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) Date(java.util.Date) BigInteger(java.math.BigInteger) JSONObject(com.alibaba.fastjson.JSONObject) Bill(com.itrus.portal.db.Bill) JSONObject(com.alibaba.fastjson.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 15 with CertInfo

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

the class CertificateController method update.

/**
 * 修改处理
 *
 * @param configuration
 * @param photoCodeImg
 * @param type
 *            新建类型 3是新建签章 2是新建证书1修改
 * @param uiModel
 * @return
 */
@RequestMapping(method = RequestMethod.POST, value = "/{type}", produces = "text/html")
public String update(@Valid EvidenceCertificate configuration, @RequestParam(value = "photoCodeImg", required = false) String photoCodeImg, @PathVariable("type") int type, Model uiModel) {
    if (type == 1) {
        // System.out.println("新建签章" + configuration.getSignatureType());
        // 获取证书信息
        EvidenceCertificate econfiguration = certificateService.selectById(configuration.getId());
        EvidenceSecretKey secretkey = new EvidenceSecretKey();
        try {
            if (StringUtils.isNotEmpty(photoCodeImg)) {
                // 获取密钥信息
                secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", econfiguration.getEvidenceSecretKey());
                File imgDir = filePathUtils.getEnterpriseFile(secretkey.getAlias());
                File frontImg = filePathUtils.saveImg(imgDir, null, photoCodeImg, IMG_DEFAULT_TYPE, IMG_NAME_VERIFY);
                if (frontImg != null && frontImg.isFile()) {
                    configuration.setPhotoCodeImg(frontImg.getName());
                    configuration.setPhotoCodeImgHash(HMACSHA1.genSha1HashOfFile(frontImg));
                }
            }
            if (configuration.getId() == null) {
                certificateService.insert(configuration);
            } else {
                String s = String.valueOf(econfiguration.getEvidenceSecretKey());
                Long keyid = Long.valueOf(s);
                EvidenceSecretKey secret = secrtkey.selectById(keyid);
                boolean is = certificateService.setSeal(secret.getAlias(), photoCodeImg);
                if (is) {
                    certificateService.update(configuration);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String oper = "修改签章失败";
            String info = "错误原因:" + e.toString();
            LogUtil.evidencelog(sqlSession, null, oper, info);
            error = "修改签章失败";
            return "redirect:/certificate/" + configuration.getId() + "/" + 3;
        }
        if (econfiguration.getIsCertificate() == null || econfiguration.getIsCertificate() != 1) {
            JSONObject ret_data = null;
            ret_data = JSONObject.parseObject(configuration.getSubject());
            String cn = ret_data.getString("userName");
            String ou = ret_data.getString("userOrgunit");
            // String emali = ret_data.getString("EMAILADDRESS");
            String O = ret_data.getString("userOrganization");
            String dn = "CN=" + cn + "OU=" + ou + "O=" + O;
            String csr = certificateService.genCsr(secretkey.getAlias(), configuration.getArithmetic(), dn);
            if (csr != null) {
                RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", configuration.getRaAccount());
                CertUtlis certutil = new CertUtlis();
                // UserInfo rauserinfo = new UserInfo();
                // Weibo类在下边定义
                UserInfo rauserinfo = JSON.parseObject(configuration.getSubject(), UserInfo.class);
                // System.out.println(rauserinfo.getUserAdditionalField1()+rauserinfo.getUserName());
                // UserInfo = (UserInfo)JSONObject.toBean(ret_data,UserInfo.class);//将建json对象转换为Person对象
                // System.out.println(configuration.getSubject());
                /*	rauserinfo.setUserName(cn);
					rauserinfo.setUserEmail(emali);
					rauserinfo.setUserAdditionalField1(ou);
					rauserinfo.setUserOrganization(O); */
                // 证书有效期
                Integer certValidity = 7;
                if ("0".equals(configuration.getPeriod())) {
                    certValidity = null;
                } else if (1 == configuration.getPeriod()) {
                    certValidity = 365 * 1 + 1;
                } else if (3 == configuration.getPeriod()) {
                    certValidity = 365 * 3 + 1;
                } else if (5 == configuration.getPeriod()) {
                    certValidity = 365 * 5 + 2;
                } else if (10 == configuration.getPeriod()) {
                    certValidity = 365 * 10 + 2;
                }
                // 调用RA
                CertInfo racertinfo = null;
                try {
                    if (ra.getAaPassword() != null) {
                        ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
                    }
                    racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    String oper = "RA调用失败";
                    String info = "错误原因:" + e.toString();
                    LogUtil.evidencelog(sqlSession, null, oper, info);
                    error = "RA调用失败";
                    return "redirect:/certificate/" + configuration.getId() + "/" + 3;
                }
                if (racertinfo != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                    EvidenceCert cert = new EvidenceCert();
                    cert.setCertBase64(racertinfo.getCertSignBuf());
                    cert.setCreateTime(new Date());
                    cert.setCertSerialnumber(racertinfo.getCertSerialNumber());
                    cert.setIssuerdn(racertinfo.getCertIssuerDn());
                    cert.setSubjectdn(racertinfo.getCertSubjectDn());
                    try {
                        configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                        configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                        cert.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                        cert.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cert.setCreateTime(new Date());
                    sqlSession.insert("com.itrus.portal.db.EvidenceCertMapper.insert", cert);
                    configuration.setCert(cert.getId().toString());
                    configuration.setCertp7(racertinfo.getCertSignBufP7());
                    configuration.setCertSerialnumber(racertinfo.getCertSerialNumber());
                    boolean is = certificateService.setCertitifate(secretkey.getAlias(), racertinfo.getCertSignBuf(), racertinfo.getCertSignBufP7());
                    if (is) {
                        if ("0".equals(configuration.getArithmetic())) {
                            configuration.setArithmetic(null);
                        }
                        if (StringUtils.isNotEmpty(configuration.getSubject())) {
                            configuration.setSubject(configuration.getSubject());
                        }
                        String s = String.valueOf(secretkey.getId());
                        int keyid = Integer.parseInt(s);
                        configuration.setEvidenceSecretKey(keyid);
                        configuration.setCreateTime(new Date());
                        configuration.setCreator(getAdmin().getName());
                        certificateService.update(configuration);
                        configuration.setSignatureType(2);
                        String oper = "证书产生成功";
                        String info = "证书名称:" + configuration.getCertificateName();
                        LogUtil.evidencelog(sqlSession, null, oper, info);
                    }
                }
            } else {
                error = "csr产生失败";
                return "redirect:/certificate/" + configuration.getId() + "/" + 3;
            }
        }
    } else if (type == 3) {
        EvidenceCertificate econfiguration = certificateService.selectById(configuration.getId());
        EvidenceSecretKey secretkey = new EvidenceSecretKey();
        try {
            if (StringUtils.isNotEmpty(photoCodeImg)) {
                // 获取密钥信息
                secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", econfiguration.getEvidenceSecretKey());
                File imgDir = filePathUtils.getEnterpriseFile(secretkey.getAlias());
                File frontImg = filePathUtils.saveImg(imgDir, null, photoCodeImg, IMG_DEFAULT_TYPE, IMG_NAME_VERIFY);
                if (frontImg != null && frontImg.isFile()) {
                    configuration.setPhotoCodeImg(frontImg.getName());
                    configuration.setPhotoCodeImgHash(HMACSHA1.genSha1HashOfFile(frontImg));
                }
            }
            if (configuration.getId() == null) {
                certificateService.insert(configuration);
            } else {
                String s = String.valueOf(econfiguration.getEvidenceSecretKey());
                Long keyid = Long.valueOf(s);
                EvidenceSecretKey secret = secrtkey.selectById(keyid);
                boolean is = certificateService.setSeal(secret.getAlias(), photoCodeImg);
                if (is) {
                    certificateService.update(configuration);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String oper = "新建签章失败";
            String info = "错误原因:" + e.toString();
            LogUtil.evidencelog(sqlSession, null, oper, info);
            error = "新建签章失败";
            return "redirect:/certificate/" + configuration.getId() + "/" + 2;
        }
    } else {
        // System.out.println("新建证书");
        EvidenceSecretKey secret = new EvidenceSecretKey();
        // List<EvidenceSecretKey> list = secrtkey.selecttype(configuration.getKeyType());
        // log.error("list="+list.size());
        // if(econfiguration.getIsCertificate()!=null && econfiguration.getIsCertificate()==1){
        /*if (list != null && list.size() != 0) {
					for (EvidenceSecretKey e : list) {
						EvidenceCertificate certificate = certificateService.selectone(e.getId());
						if (certificate == null) {
							secret.setAlias(e.getAlias());
							secret.setId(e.getId());
							break;
						}
					}
					if (StringUtils.isEmpty(secret.getAlias())) {
						List<EvidenceSecretKey> secter = secrtkey.certufucateInterface(getAdmin().getName());
						//List<EvidenceSecretKey> lists = secrtkey.selecttype(configuration.getKeyType());
						if (secter != null) {
							for (EvidenceSecretKey e : secter) {
								EvidenceCertificate certificate = certificateService.selectone(e.getId());
								if (certificate == null) {
									secret.setAlias(e.getAlias());
									secret.setId(e.getId());
									break;
								}
							}
						}
					}
				} else */
        {
            /*EvidenceSecretKey*/
            secret = secrtkey.certufucateInterface(getAdmin().getName(), configuration.getKeyType());
        // List<EvidenceSecretKey> lists = secrtkey.selecttype(configuration.getKeyType());
        /*if (secter != null) {
						for (EvidenceSecretKey e : secter) {
							EvidenceCertificate certificate = certificateService.selectone(e.getId());
							if (certificate == null) {
								secret.setAlias(e.getAlias());
								secret.setId(e.getId());
								break;
							}
						}
					}*/
        }
        /*	}else{
				 secret = sqlSession.selectOne(
						"com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey",
						econfiguration.getEvidenceSecretKey());
			}*/
        JSONObject ret_data = null;
        ret_data = JSONObject.parseObject(configuration.getSubject());
        String cn = ret_data.getString("userName");
        String ou = ret_data.getString("userOrgunit");
        // String emali = ret_data.getString("EMAILADDRESS");
        String O = ret_data.getString("userOrganization");
        String dn = "CN=" + cn + "OU=" + ou + "O=" + O;
        log.error("Alias=" + secret.getAlias() + ",Arithmetic=" + configuration.getArithmetic());
        String csr = certificateService.genCsr(secret.getAlias(), configuration.getArithmetic(), dn);
        log.error("csr=" + csr);
        if (csr != null) {
            RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", configuration.getRaAccount());
            CertUtlis certutil = new CertUtlis();
            // UserInfo rauserinfo = new UserInfo();
            // System.out.println(configuration.getSubject());
            // Weibo类在下边定义
            UserInfo rauserinfo = JSON.parseObject(configuration.getSubject(), UserInfo.class);
            // System.out.println(rauserinfo.getUserAdditionalField1()+rauserinfo.getUserName());
            /*rauserinfo.setUserName(cn);
				rauserinfo.setUserEmail(emali);
				rauserinfo.setUserAdditionalField1(ou);
				rauserinfo.setUserOrganization(O);*/
            // 证书有效期
            Integer certValidity = 7;
            if ("0".equals(configuration.getPeriod())) {
                certValidity = null;
            } else if (1 == configuration.getPeriod()) {
                certValidity = 365 * 1 + 1;
            } else if (3 == configuration.getPeriod()) {
                certValidity = 365 * 3 + 1;
            } else if (5 == configuration.getPeriod()) {
                certValidity = 365 * 5 + 2;
            } else if (10 == configuration.getPeriod()) {
                certValidity = 365 * 10 + 2;
            }
            // 调用RA
            CertInfo racertinfo = null;
            try {
                if (ra.getAaPassword() != null) {
                    ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
                }
                racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
                log.error("racertinfo=" + racertinfo);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                String oper = "RA调用失败";
                String info = "错误原因:" + e.toString();
                LogUtil.evidencelog(sqlSession, null, oper, info);
                uiModel.addAttribute("error", "RA调用失败");
                return "certificate/create";
            }
            if (racertinfo != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                EvidenceCert cert = new EvidenceCert();
                cert.setCertBase64(racertinfo.getCertSignBuf());
                cert.setCreateTime(new Date());
                cert.setCertSerialnumber(racertinfo.getCertSerialNumber());
                cert.setIssuerdn(racertinfo.getCertIssuerDn());
                cert.setSubjectdn(racertinfo.getCertSubjectDn());
                cert.setCreateTime(new Date());
                try {
                    configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                    configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                    cert.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                    cert.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                sqlSession.insert("com.itrus.portal.db.EvidenceCertMapper.insert", cert);
                configuration.setCert(cert.getId().toString());
                // configuration.setCert(racertinfo.getCertSignBuf());
                configuration.setCertp7(racertinfo.getCertSignBufP7());
                configuration.setCertSerialnumber(racertinfo.getCertSerialNumber());
                /*try {
						configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
						configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
                boolean is = certificateService.setCertitifate(secret.getAlias(), racertinfo.getCertSignBuf(), racertinfo.getCertSignBufP7());
                if (is) {
                    if ("0".equals(configuration.getArithmetic())) {
                        configuration.setArithmetic(null);
                    }
                    if (StringUtils.isNotEmpty(configuration.getSubject())) {
                        configuration.setSubject(configuration.getSubject());
                    }
                    String s = String.valueOf(secret.getId());
                    int keyid = Integer.parseInt(s);
                    configuration.setEvidenceSecretKey(keyid);
                    configuration.setCreateTime(new Date());
                    configuration.setCreator(getAdmin().getName());
                    certificateService.insert(configuration);
                    String oper = "证书产生成功";
                    String info = "证书名称:" + configuration.getCertificateName();
                    LogUtil.evidencelog(sqlSession, null, oper, info);
                    EvidenceCertificateExample certE = new EvidenceCertificateExample();
                    EvidenceCertificateExample.Criteria tificate = certE.createCriteria();
                    tificate.andEvidenceSecretKeyEqualTo(keyid);
                    configuration = sqlSession.selectOne("com.itrus.portal.db.EvidenceCertificateMapper.selectByExample", certE);
                }
            }
        } else {
            uiModel.addAttribute("error", "csr产生失败");
            return "certificate/create";
        }
    }
    return "redirect:/certificate/" + configuration.getId() + "/" + 1;
// return "redirect:/certificate/show/"+configuration.getId()+"/"+1;
// return "redirect:/certificate";
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) UserInfo(cn.topca.tca.ra.service.UserInfo) EvidenceSecretKey(com.itrus.portal.db.EvidenceSecretKey) ParseException(java.text.ParseException) IOException(java.io.IOException) Date(java.util.Date) CertUtlis(com.itrus.portal.utils.CertUtlis) EvidenceCert(com.itrus.portal.db.EvidenceCert) JSONObject(com.alibaba.fastjson.JSONObject) RaAccount(com.itrus.portal.db.RaAccount) EvidenceCertificateExample(com.itrus.portal.db.EvidenceCertificateExample) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) ParseException(java.text.ParseException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

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