Search in sources :

Example 1 with RaServiceUnavailable_Exception

use of cn.topca.tca.ra.service.RaServiceUnavailable_Exception 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 2 with RaServiceUnavailable_Exception

use of cn.topca.tca.ra.service.RaServiceUnavailable_Exception 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 3 with RaServiceUnavailable_Exception

use of cn.topca.tca.ra.service.RaServiceUnavailable_Exception 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 4 with RaServiceUnavailable_Exception

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

the class MobileCertificateService method revokeCertByApi.

// api方式吊销证书
private void revokeCertByApi(RaAccount raAccount, MobileCertificate mobileCert) throws RaServiceUnavailable_Exception {
    // 创建RaCertManager类
    RaCertManager raCertManager = RaFactory.getRaCertManager(raAccount.getAccountOrganization(), raAccount.getAccountOrgUnit());
    raCertManager.setAccountHash(raAccount.getAccountHash());
    // 设置RA服务IP地址、端口号和协议等
    raCertManager.addRaService(raAccount.getServiceUrl());
    RevokeResult revokeResult = null;
    try {
        // 对证书序列号进行一次转换,适应ICA的证书序列号方式
        revokeResult = raCertManager.revokeCert(CertUtils.getICAValidSerialNumber(mobileCert.getSequenceNumber()), ComNames.AA_PASS_PORT, RevokeReasonEnum.KeyCompromise);
        if (!revokeResult.isSuccess())
            throw new RaServiceUnavailable_Exception(revokeResult.getMessage());
    } catch (RaServiceUnavailable e) {
        // 服务全部停止
        throw new RaServiceUnavailable_Exception(e.getMessage());
    }
}
Also used : RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) RaCertManager(com.itrus.raapi.RaCertManager) RaServiceUnavailable(com.itrus.raapi.exception.RaServiceUnavailable) RevokeResult(com.itrus.raapi.result.RevokeResult)

Example 5 with RaServiceUnavailable_Exception

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

the class CertUtlis method enrollCertByWS.

public CertInfo enrollCertByWS(String csr, RaAccount raAccount, UserInfo userInfo, Integer certValidity) throws MalformedURLException, RaServiceUnavailable_Exception, TerminalServiceException {
    String json = "{\"certValidity\":" + certValidity + "}";
    CertInfo certInfo = null;
    UserAPIService service = new UserAPIService(new URL(raAccount.getServiceUrl()));
    UserAPIServicePortType client = service.getUserAPIServicePort();
    // 用户信息
    try {
        logger.error("***判断是什么模式***" + raAccount.getCertSignType());
        // 判断是什么模式
        if (raAccount.getCertSignType() == null || (raAccount.getCertSignType() != null && raAccount.getCertSignType() == 1)) {
            // AA模式
            logger.error("*****userInfo=" + userInfo + "***csr***=" + csr + "***raAccount.getAccountHash()**=" + raAccount.getAccountHash() + "***raAccount.getAaPassword()**=" + raAccount.getAaPassword() + "**json**=" + json);
            certInfo = client.enrollCertAA(userInfo, csr, raAccount.getAccountHash(), raAccount.getAaPassword(), "", json);
        } else {
            // passcord模式
            logger.error("输出hash*****raAccount.getAccountHash()========" + raAccount.getAccountHash());
            // 判断是否为passcord模式
            CaPasscode passcode = new CaPasscode();
            // 获取对应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 = raAccountInfoService.getRaAccountInfo(raInfoExample);
            // 获取对应passcode
            try {
                passcode = codeService.IssuedCode4Cert(raAccountInfo);
                if (passcode == null) {
                    logger.error("******passcode为空***********");
                    throw new TerminalServiceException("passcode为空");
                }
            } catch (TerminalServiceException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                throw e1;
            }
            logger.error("******passcode=" + passcode.getPasscode());
            certInfo = client.enrollCertAA(userInfo, csr, raAccount.getAccountHash(), raAccount.getAaPassword(), passcode.getPasscode(), json);
        }
    } catch (RaServiceUnavailable_Exception e) {
        logger.error("userInfo:" + ToStringBuilder.reflectionToString(userInfo));
        logger.error("csr:" + csr);
        logger.error("raAccount:" + ToStringBuilder.reflectionToString(raAccount));
        logger.error("json:" + json);
        throw e;
    }
    return certInfo;
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) RaAccountInfo(com.itrus.portal.db.RaAccountInfo) RaAccountInfoExample(com.itrus.portal.db.RaAccountInfoExample) TerminalServiceException(com.itrus.portal.exception.TerminalServiceException) RaServiceUnavailable_Exception(cn.topca.tca.ra.service.RaServiceUnavailable_Exception) UserAPIServicePortType(cn.topca.tca.ra.service.UserAPIServicePortType) CaPasscode(com.itrus.portal.db.CaPasscode) UserAPIService(cn.topca.tca.ra.service.UserAPIService) URL(java.net.URL)

Aggregations

RaServiceUnavailable_Exception (cn.topca.tca.ra.service.RaServiceUnavailable_Exception)5 CertInfo (cn.topca.tca.ra.service.CertInfo)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 JSONArray (com.alibaba.fastjson.JSONArray)2 JSONObject (com.alibaba.fastjson.JSONObject)2 EncDecException (com.itrus.portal.exception.EncDecException)2 TerminalServiceException (com.itrus.portal.exception.TerminalServiceException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 UserAPIService (cn.topca.tca.ra.service.UserAPIService)1 UserAPIServicePortType (cn.topca.tca.ra.service.UserAPIServicePortType)1 UserInfo (cn.topca.tca.ra.service.UserInfo)1 SigningServerException (com.itrus.cryptorole.SigningServerException)1 Bill (com.itrus.portal.db.Bill)1 CaPasscode (com.itrus.portal.db.CaPasscode)1 CertBuf (com.itrus.portal.db.CertBuf)1 DigitalCert (com.itrus.portal.db.DigitalCert)1 Product (com.itrus.portal.db.Product)1