cn.hutool.crypto.SecureUtil Java Examples

The following examples show how to use cn.hutool.crypto.SecureUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityTools.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
public static SecurityResp valid(SecurityReq req) {
    SecurityResp resp=new SecurityResp();
    String pubKey=req.getPubKey();
    String aesKey=req.getAesKey();
    String data=req.getData();
    String signData=req.getSignData();
    RSA rsa=new RSA(null, Base64Decoder.decode(pubKey));
    Sign sign= new Sign(SignAlgorithm.SHA1withRSA,null,pubKey);



    byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey);
    //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes));
    AES aes = SecureUtil.aes(decryptAes);

    String dencrptValue =aes.decryptStr(data);
    //log.info("解密后报文"+dencrptValue);
    resp.setData(new JSONObject(dencrptValue));

    boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData));
    resp.setSuccess(verify);
    return resp;
}
 
Example #2
Source File: TomcatEditController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 添加Tomcat
 *
 * @param tomcatInfoModel Tomcat信息
 * @return 操作结果
 */
@RequestMapping(value = "add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String add(TomcatInfoModel tomcatInfoModel) {
    // 根据Tomcat名称查询tomcat是否已经存在
    String name = tomcatInfoModel.getName();
    TomcatInfoModel tomcatInfoModelTemp = tomcatEditService.getItemByName(name);
    if (tomcatInfoModelTemp != null) {
        return JsonMessage.getString(401, "名称已经存在,请使用其他名称!");
    }
    tomcatInfoModel.setId(SecureUtil.md5(DateUtil.now()));
    tomcatInfoModel.setCreator(getUserName());

    // 设置tomcat路径,去除多余的符号
    tomcatInfoModel.setPath(FileUtil.normalize(tomcatInfoModel.getPath()));
    Objects.requireNonNull(tomcatInfoModel.pathAndCheck());
    tomcatEditService.addItem(tomcatInfoModel);
    tomcatInfoModel.initTomcat();
    return JsonMessage.getString(200, "保存成功");
}
 
Example #3
Source File: OcrUtils.java    From tools-ocr with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String sogouWebOcr(byte[] imgData) {
    String url = "https://deepi.sogou.com/api/sogouService";
    String referer = "https://deepi.sogou.com/?from=picsearch&tdsourcetag=s_pctim_aiomsg";
    String imageData = Base64.encode(imgData);
    long t = System.currentTimeMillis();
    String sign = SecureUtil.md5("sogou_ocr_just_for_deepibasicOpenOcr" + t + imageData.substring(0, Math.min(1024, imageData.length())) + "4b66a37108dab018ace616c4ae07e644");
    Map<String, Object> data = new HashMap<>();
    data.put("image", imageData);
    data.put("lang", "zh-Chs");
    data.put("pid", "sogou_ocr_just_for_deepi");
    data.put("salt", t);
    data.put("service", "basicOpenOcr");
    data.put("sign", sign);
    HttpRequest request = HttpUtil.createPost(url).timeout(15000);
    request.form(data);
    request.header("Referer", referer);
    HttpResponse response = request.execute();
    return extractSogouResult(WebUtils.getSafeHtml(response));
}
 
Example #4
Source File: BaseCryptoAutoConfig.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@Autowired
private void init(CryptoProperties cryptoProperties) {
	// AES
	String aes_keyt = cryptoProperties.getAesKeyt();
	if (StringUtils.isNotEmpty(aes_keyt)) {
		Singleton.put(SecureUtil.aes(aes_keyt.getBytes()));
		log.info("【初始化工具-SecureSingleton】AES单例配置 ... 已初始化完毕。");
	}
	
	// RSA
	String rsa_public_keyt = cryptoProperties.getRsaPublicKeyt();
	String rsa_private_keyt = cryptoProperties.getRsaPrivateKeyt();
	if (StringUtils.isNotEmpty(rsa_public_keyt) || StringUtils.isNotEmpty(rsa_private_keyt)) {
		Singleton.put(SecureUtil.rsa(rsa_private_keyt, rsa_public_keyt));
		log.info("【初始化工具-SecureSingleton】RSA单例配置 ... 已初始化完毕。");
	}
}
 
Example #5
Source File: InstallController.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
private User createUser(InstallParam installParam) {
    // Get user
    return userService.getCurrentUser().map(user -> {
        // Update this user
        installParam.update(user);
        // Set password manually
        userService.setPassword(user, installParam.getPassword());
        // Update user
        return userService.update(user);
    }).orElseGet(() -> {
        String gravatar = "//cn.gravatar.com/avatar/" + SecureUtil.md5(installParam.getEmail()) +
            "?s=256&d=mm";
        installParam.setAvatar(gravatar);
        return userService.createBy(installParam);
    });
}
 
Example #6
Source File: UserController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 处理修改密码的请求
 *
 * @param beforePass 旧密码
 * @param newPass    新密码
 * @param userId     用户编号
 * @param session    session
 * @return JsonResult
 */
@PostMapping(value = "changePass")
@ResponseBody
public JsonResult changePass(@ModelAttribute("beforePass") String beforePass,
                             @ModelAttribute("newPass") String newPass,
                             @ModelAttribute("userId") Long userId,
                             HttpSession session) {
    try {
        User user = userService.findByUserIdAndUserPass(userId, SecureUtil.md5(beforePass));
        if (null != user) {
            user.setUserPass(SecureUtil.md5(newPass));
            userService.save(user);
            session.removeAttribute(HaloConst.USER_SESSION_KEY);
        } else {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.user.old-password-error"));
        }
    } catch (Exception e) {
        log.error("Password change failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.user.update-password-failed"));
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.user.update-password-success"));
}
 
Example #7
Source File: OpenApiInterceptor.java    From Jpom with MIT License 6 votes vote down vote up
private boolean checkOpenApi(HttpServletRequest request, HttpServletResponse response) {
    String header = request.getHeader(ServerOpenApi.HEAD);
    if (StrUtil.isEmpty(header)) {
        ServletUtil.write(response, JsonMessage.getString(300, "token empty"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    String authorizeToken = ServerExtConfigBean.getInstance().getAuthorizeToken();
    if (StrUtil.isEmpty(authorizeToken)) {
        ServletUtil.write(response, JsonMessage.getString(300, "not config token"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    String md5 = SecureUtil.md5(authorizeToken);
    md5 = SecureUtil.sha1(md5 + ServerOpenApi.HEAD);
    if (!StrUtil.equals(header, md5)) {
        ServletUtil.write(response, JsonMessage.getString(300, "not config token"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    return true;
}
 
Example #8
Source File: SecurityTools.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
public static SecurityResp valid(SecurityReq req) {
    SecurityResp resp=new SecurityResp();
    String pubKey=req.getPubKey();
    String aesKey=req.getAesKey();
    String data=req.getData();
    String signData=req.getSignData();
    RSA rsa=new RSA(null, Base64Decoder.decode(pubKey));
    Sign sign= new Sign(SignAlgorithm.SHA1withRSA,null,pubKey);



    byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey);
    //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes));
    AES aes = SecureUtil.aes(decryptAes);

    String dencrptValue =aes.decryptStr(data);
    //log.info("解密后报文"+dencrptValue);
    resp.setData(new JSONObject(dencrptValue));

    boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData));
    resp.setSuccess(verify);
    return resp;
}
 
Example #9
Source File: GlobalUserServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * @param data
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public GlobalUser update(GlobalUserUpdateDTO data) {
    if (StrUtil.isNotBlank(data.getPassword()) || StrUtil.isNotBlank(data.getPassword())) {
        BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
    }

    GlobalUser globalUser = BeanPlusUtil.toBean(data, GlobalUser.class);
    if (StrUtil.isNotBlank(data.getPassword())) {
        String md5Password = SecureUtil.md5(data.getPassword());
        globalUser.setPassword(md5Password);

    }
    updateById(globalUser);
    return globalUser;
}
 
Example #10
Source File: GlobalUserServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * @param data
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public GlobalUser save(GlobalUserSaveDTO data) {
    BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
    isFalse(check(data.getAccount()), "账号已经存在");

    String md5Password = SecureUtil.md5(data.getPassword());

    GlobalUser globalAccount = BeanPlusUtil.toBean(data, GlobalUser.class);
    // 全局表就不存用户数据了
    globalAccount.setPassword(md5Password);
    globalAccount.setName(StrHelper.getOrDef(data.getName(), data.getAccount()));
    globalAccount.setReadonly(false);

    save(globalAccount);
    return globalAccount;
}
 
Example #11
Source File: GlobalUserServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * @param data
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public GlobalUser save(GlobalUserSaveDTO data) {
    BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
    isFalse(check(data.getAccount()), "账号已经存在");

    String md5Password = SecureUtil.md5(data.getPassword());

    GlobalUser globalAccount = BeanPlusUtil.toBean(data, GlobalUser.class);
    // 全局表就不存用户数据了
    globalAccount.setPassword(md5Password);
    globalAccount.setName(StrHelper.getOrDef(data.getName(), data.getAccount()));
    globalAccount.setReadonly(false);

    save(globalAccount);
    return globalAccount;
}
 
Example #12
Source File: UserController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 处理修改密码的请求
 *
 * @param beforePass 旧密码
 * @param newPass    新密码
 * @param userId     用户编号
 * @param session    session
 * @return JsonResult
 */
@PostMapping(value = "changePass")
@ResponseBody
public JsonResult changePass(@ModelAttribute("beforePass") String beforePass,
                             @ModelAttribute("newPass") String newPass,
                             @ModelAttribute("userId") Long userId,
                             HttpSession session) {
    try {
        final User user = userService.findByUserIdAndUserPass(userId, SecureUtil.md5(beforePass));
        if (null != user) {
            user.setUserPass(SecureUtil.md5(newPass));
            userService.save(user);
            session.removeAttribute(HaloConst.USER_SESSION_KEY);
        } else {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.user.old-password-error"));
        }
    } catch (Exception e) {
        log.error("Password change failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.user.update-password-failed"));
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.user.update-password-success"));
}
 
Example #13
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 6 votes vote down vote up
public PublicKey loadPublicKey(String path){
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte buffer[] = new byte[16];
		int size;
		while ((size = fis.read(buffer)) != -1) {
			baos.write(buffer, 0, size);
		}
		fis.close();
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		return SecureUtil.generatePublicKey("SM2", decode);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #14
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * 从本地导入私钥
 * 
 * @param path
 * @return
 */
public BigInteger importPrivateKey(String path) {
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		byte[] dest = new byte[32];
		System.arraycopy(decode, 36, dest, 0, 32);
		System.out.println(Util.bytesToHexString(dest));
		PrivateKey key = SecureUtil.generatePrivateKey("SM2", decode);
		System.out.println("[importPrivateKey]alg:" + key.getAlgorithm());
		System.out.println("privatekey:" + ((BCECPrivateKey) key).getD());
		BigInteger b = ((BCECPrivateKey) key).getD();
		ECPoint g2 = ((BCECPrivateKey) key).getParameters().getG();
		System.out.println("[importPrivateKey]x:" + Util.bytesToHexString(g2.getXCoord().getEncoded()));
		System.out.println("[importPrivateKey]y:" + Util.bytesToHexString(g2.getYCoord().getEncoded()));
		System.out.println(Util.bytesToHexString(b.toByteArray()));
		return b;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #15
Source File: OauthServiceImpl.java    From plumemo with Apache License 2.0 6 votes vote down vote up
@Override
public Result updatePassword(AuthUserVO authUserVO) {

    if (StringUtils.isBlank(authUserVO.getPassword()) || StringUtils.isBlank(authUserVO.getPasswordOld())) {
        ExceptionUtil.isRollback(true, ErrorEnum.PARAM_ERROR);
    }

    UserSessionVO userSessionInfo = SessionUtil.getUserSessionInfo();

    AuthUser authUser = authUserDao.selectById(userSessionInfo.getId());
    if (!SecureUtil.md5(authUserVO.getPasswordOld()).equals(authUser.getPassword())) {
        ExceptionUtil.isRollback(true, ErrorEnum.UPDATE_PASSWORD_ERROR);
    }

    authUserDao.updateById(new AuthUser().setId(userSessionInfo.getId()).setPassword(SecureUtil.md5(authUserVO.getPassword())));

    return Result.createWithSuccessMessage();
}
 
Example #16
Source File: SecurityTools.java    From teaching with Apache License 2.0 6 votes vote down vote up
public static SecurityResp valid(SecurityReq req) {
    SecurityResp resp=new SecurityResp();
    String pubKey=req.getPubKey();
    String aesKey=req.getAesKey();
    String data=req.getData();
    String signData=req.getSignData();
    RSA rsa=new RSA(null, Base64Decoder.decode(pubKey));
    Sign sign= new Sign(SignAlgorithm.SHA1withRSA,null,pubKey);



    byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey);
    //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes));
    AES aes = SecureUtil.aes(decryptAes);

    String dencrptValue =aes.decryptStr(data);
    //log.info("解密后报文"+dencrptValue);
    resp.setData(new JSONObject(dencrptValue));

    boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData));
    resp.setSuccess(verify);
    return resp;
}
 
Example #17
Source File: TieBaLiveApi.java    From tieba-api with MIT License 6 votes vote down vote up
/**
 * 公共请求方法
 * @param url
 * @param bduss
 * @param stoken
 * @param params
 * @return
 */
public static JSONObject commonRequest(String url, String bduss, String stoken, String... params) {
	HttpRequest request = HttpRequest.post(url)
			.form("BDUSS", bduss)
			.form("stoken", stoken)
			.form("_client_version", "10.3.8.1")
			.form("_client_type", 2)
			.form("timestamp", System.currentTimeMillis());
	for (String param : params) {
		request.form(StrUtil.subBefore(param, "=", false), StrUtil.subAfter(param, "=", false));
	}
	request.form("tbs", getTbs(bduss));
	Map<String, Object> formMap = request.form();
	formMap = MapUtil.sort(formMap);
	StringBuilder sb = new StringBuilder();
	for (String key : formMap.keySet()) {
		sb.append(String.format("%s=%s", key, formMap.get(key)).toString());
	}
	sb.append("tiebaclient!!!");
	String sign = SecureUtil.md5(sb.toString()).toUpperCase();
	String body = request.form("sign", sign).execute().body();
	if(StrUtil.isNotBlank(body)) {
		return JSON.parseObject(body);
	}
	return null;
}
 
Example #18
Source File: AdminUiService.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 超管账号登录
 *
 * @param account  账号
 * @param password 密码
 * @return
 */
public R<AuthInfo> adminLogin(String account, String password) {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);

    GlobalUser user = this.globalUserService.getOne(Wrappers.<GlobalUser>lambdaQuery()
            .eq(GlobalUser::getAccount, account).eq(GlobalUser::getTenantCode, BizConstant.SUPER_TENANT));
    // 密码错误
    if (user == null) {
        throw new BizException(ExceptionCode.JWT_USER_INVALID.getCode(), ExceptionCode.JWT_USER_INVALID.getMsg());
    }

    String passwordMd5 = SecureUtil.md5(password);
    if (!user.getPassword().equalsIgnoreCase(passwordMd5)) {
        return R.fail("用户名或密码错误!");
    }
    JwtUserInfo userInfo = new JwtUserInfo(user.getId(), user.getAccount(), user.getName());

    AuthInfo authInfo = tokenUtil.createAuthInfo(userInfo, null);
    log.info("token={}", authInfo.getToken());
    return R.success(authInfo);
}
 
Example #19
Source File: GlobalUserServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * @param data
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public GlobalUser update(GlobalUserUpdateDTO data) {
    if (StrUtil.isNotBlank(data.getPassword()) || StrUtil.isNotBlank(data.getPassword())) {
        BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
    }

    GlobalUser globalUser = BeanPlusUtil.toBean(data, GlobalUser.class);
    if (StrUtil.isNotBlank(data.getPassword())) {
        String md5Password = SecureUtil.md5(data.getPassword());
        globalUser.setPassword(md5Password);

    }
    updateById(globalUser);
    return globalUser;
}
 
Example #20
Source File: AdminUiService.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 超管账号登录
 *
 * @param account  账号
 * @param password 密码
 * @return
 */
public R<AuthInfo> adminLogin(String account, String password) {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);

    GlobalUser user = this.globalUserService.getOne(Wrappers.<GlobalUser>lambdaQuery()
            .eq(GlobalUser::getAccount, account).eq(GlobalUser::getTenantCode, BizConstant.SUPER_TENANT));
    // 密码错误
    if (user == null) {
        throw new BizException(ExceptionCode.JWT_USER_INVALID.getCode(), ExceptionCode.JWT_USER_INVALID.getMsg());
    }

    String passwordMd5 = SecureUtil.md5(password);
    if (!user.getPassword().equalsIgnoreCase(passwordMd5)) {
        return R.fail("用户名或密码错误!");
    }
    JwtUserInfo userInfo = new JwtUserInfo(user.getId(), user.getAccount(), user.getName());

    AuthInfo authInfo = tokenUtil.createAuthInfo(userInfo, null);
    log.info("token={}", authInfo.getToken());
    return R.success(authInfo);
}
 
Example #21
Source File: InstallController.java    From zfile with MIT License 5 votes vote down vote up
@PostMapping("/install")
public ResultBean install(SystemConfigDTO systemConfigDTO) {
    if (!StringUtils.isEmpty(systemConfigService.getAdminUsername())) {
        return ResultBean.error("请勿重复初始化.");
    }

    systemConfigDTO.setPassword(SecureUtil.md5(systemConfigDTO.getPassword()));
    systemConfigService.updateSystemConfig(systemConfigDTO);

    return ResultBean.success();
}
 
Example #22
Source File: UserDaoTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试保存
 */
@Test
public void testSave() {
    String salt = IdUtil.fastSimpleUUID();
    User testSave3 = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).build();
    userDao.save(testSave3);

    Assert.assertNotNull(testSave3.getId());
    Optional<User> byId = userDao.findById(testSave3.getId());
    Assert.assertTrue(byId.isPresent());
    log.debug("【byId】= {}", byId.get());
}
 
Example #23
Source File: UserDaoTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 初始化10条数据
 */
private void initData() {
    List<User> userList = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        String salt = IdUtil.fastSimpleUUID();
        int index = 3 + i;
        User user = User.builder().name("testSave" + index).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + index + "@xkcoding.com").phoneNumber("1730000000" + index).status(1).lastLoginTime(new DateTime()).build();
        userList.add(user);
    }
    userDao.saveAll(userList);
}
 
Example #24
Source File: UserMapperTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试通用Mapper - 保存
 */
@Test
public void testInsert() {
    String salt = IdUtil.fastSimpleUUID();
    User testSave3 = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
    userMapper.insertUseGeneratedKeys(testSave3);
    Assert.assertNotNull(testSave3.getId());
    log.debug("【测试主键回写#testSave3.getId()】= {}", testSave3.getId());
}
 
Example #25
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * 从本地导入公钥
 * @param path
 * @return
 */
public ECPoint importPublicKey(String path) {
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte buffer[] = new byte[16];
		int size;
		while ((size = fis.read(buffer)) != -1) {
			baos.write(buffer, 0, size);
		}
		fis.close();
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		PublicKey pub = SecureUtil.generatePublicKey("SM2", decode);
		System.out.println(pub.getClass());
		ECPoint point = ((BCECPublicKey)pub).getQ();
		byte[] qBytes = point.getEncoded(false);
		System.out.println("[importpubkey]test_point:" + Util.bytesToHexString(qBytes));
		return curve.decodePoint(qBytes);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #26
Source File: SystemConfigService.java    From zfile with MIT License 5 votes vote down vote up
/**
 * 更新后台账号密码
 *
 * @param   username
 *          用户名
 *
 * @param   password
 *          密码
 */
public void updateUsernameAndPwd(String username, String password) {
    SystemConfig usernameConfig = systemConfigRepository.findByKey(SystemConfigConstant.USERNAME);
    usernameConfig.setValue(username);
    systemConfigRepository.save(usernameConfig);

    String encryptionPassword = SecureUtil.md5(password);
    SystemConfig systemConfig = systemConfigRepository.findByKey(SystemConfigConstant.PASSWORD);
    systemConfig.setValue(encryptionPassword);

    zFileCache.removeConfig();

    systemConfigRepository.save(systemConfig);
}
 
Example #27
Source File: UserServiceTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void saveUserList() {
    List<User> users = Lists.newArrayList();
    for (int i = 5; i < 15; i++) {
        String salt = IdUtil.fastSimpleUUID();
        User user = User.builder().name("testSave" + i).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
        users.add(user);
    }
    userService.saveUserList(users);
    Assert.assertTrue(userService.getUserList().size() > 2);
}
 
Example #28
Source File: OauthServiceImpl.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public Result saveUserByGithub(AuthUserVO authUserVO) {
    log.debug("saveUserByGithub {}", authUserVO);
    if (authUserVO == null || StringUtils.isBlank(authUserVO.getSocialId())) {
        ExceptionUtil.rollback(ErrorEnum.PARAM_ERROR);
    }

    AuthUser authUser = authUserDao.selectOne(new LambdaQueryWrapper<AuthUser>().eq(AuthUser::getSocialId, authUserVO.getSocialId()));
    if (authUser == null) {
        authUser = new AuthUser();
        authUser.setSocialId(authUserVO.getSocialId());
        authUser.setAvatar(authUserVO.getAvatar());
        authUser.setName(authUserVO.getName());
        authUser.setRoleId(RoleEnum.USER.getRoleId());
        authUser.setPassword(SecureUtil.hmacMd5(RandomStringUtils.random(32)).digestHex(authUserVO.getSocialId()));
        authUser.setCreateTime(LocalDateTime.now());
        authUserDao.insert(authUser);
    } else {
        if (Constants.ONE == ToolUtil.getInteger(authUser.getStatus())) {
            ExceptionUtil.rollback(ErrorEnum.LOGIN_DISABLE);
        }
    }
    authUserVO.setCreateTime(LocalDateTime.now());
    String token = JwtUtil.getToken(new AuthUserVO().setPassword(authUser.getPassword()).setName(authUser.getName()).setId(authUser.getId()));

    authUserVO.setToken(token);
    authTokenDao.insert(new AuthToken().setUserId(authUser.getId()).setToken(token).setExpireTime(new Date(Constants.EXPIRE_TIME + System.currentTimeMillis()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime()));
    return Result.createWithModel(authUserVO);
}
 
Example #29
Source File: UserServiceTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void saveUser() {
    String salt = IdUtil.fastSimpleUUID();
    User user = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();

    user = userService.saveUser(user);
    Assert.assertTrue(ObjectUtil.isNotNull(user.getId()));
    log.debug("【user】= {}", user);
}
 
Example #30
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 5 votes vote down vote up
public PrivateKey loadPrivateKey(String path){
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		return SecureUtil.generatePrivateKey("SM2", decode);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}