cn.hutool.crypto.asymmetric.KeyType Java Examples

The following examples show how to use cn.hutool.crypto.asymmetric.KeyType. 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: UserController.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@ApiOperation("修改密码")
@PostMapping(value = "/updatePass")
public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) {
    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
    String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
    UserDTO user = userService.findByName(SecurityUtils.getCurrentUsername());
    if (!passwordEncoder.matches(oldPass, user.getPassword())) {
        throw new SkException("修改失败,旧密码错误");
    }
    if (passwordEncoder.matches(newPass, user.getPassword())) {
        throw new SkException("新密码不能与旧密码相同");
    }
    userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass));
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #2
Source File: AccoutResource.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 修改密码
 * POST  /account/changePassword : changes the current user's password
 *
 * @param passwordChangeVo the passwordVo
 */
@ApiOperation(value = "修改密码")
@PostMapping(path = "/account/change-password")
public Result changePassword(@Valid @RequestBody PasswordChangeVo passwordChangeVo) {
	// 密码解密
	RSA rsa = new RSA(applicationProperties.getRsa().getPrivateKey(), applicationProperties.getRsa().getPublicKey());
	String oldPass = new String(rsa.decrypt(passwordChangeVo.getOldPassword(), KeyType.PrivateKey));
	String newPass = new String(rsa.decrypt(passwordChangeVo.getNewPassword(), KeyType.PrivateKey));
	String confirmPass = new String(rsa.decrypt(passwordChangeVo.getConfirmPassword(), KeyType.PrivateKey));
	passwordChangeVo.setNewPassword(newPass);
	passwordChangeVo.setConfirmPassword(confirmPass);
	passwordChangeVo.setOldPassword(oldPass);
	userService.changePassword(SecurityUtil.getUser().getUsername(),
		passwordChangeVo);
	return Result.buildOk("密码修改成功,请重新登录");
}
 
Example #3
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 #4
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 #5
Source File: SysUserController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Log("修改邮箱")
@ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}")
public ResponseEntity<Object> updateEmail(@PathVariable String code,@RequestBody User user){

    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String password = new String(rsa.decrypt(user.getPassword(), KeyType.PrivateKey));
    UserDto userDto = userService.findByName(SecurityUtils.getUsername());
    if(!passwordEncoder.matches(password, userDto.getPassword())){
        throw new BadRequestException("密码错误");
    }
    VerificationCode verificationCode = new VerificationCode(code, YshopConstant.RESET_MAIL,"email",user.getEmail());
    verificationCodeService.validated(verificationCode);
    userService.updateEmail(userDto.getUsername(),user.getEmail());
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #6
Source File: SysUserController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@ApiOperation("修改密码")
@PostMapping(value = "/updatePass")
public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo){

    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
    String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
    UserDto user = userService.findByName(SecurityUtils.getUsername());
    if(!passwordEncoder.matches(oldPass, user.getPassword())){
        throw new BadRequestException("修改失败,旧密码错误");
    }
    if(passwordEncoder.matches(newPass, user.getPassword())){
        throw new BadRequestException("新密码不能与旧密码相同");
    }
    userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #7
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 #8
Source File: SecurityTools.java    From jeecg-cloud 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: TestCert.java    From Jpom with MIT License 6 votes vote down vote up
public static void main(String[] args) {
//        HttpRequest request = HttpUtil.createPost("https://myssl.com/api/v1/tools/cert_decode");
//        request.form("certfile", new File("D:\\SystemDocument\\Desktop\\web_hulianwangjia\\full_chain.pem"));
//        request.form("type", "upload");
//        HttpResponse response = request.execute();
//        System.out.println(response.body());
//        D:\SystemDocument\Desktop

        PrivateKey privateKey = PemUtil.readPemPrivateKey(ResourceUtil.getStream("D:\\SystemDocument\\Desktop\\1979263_jpom.keepbx.cn.key"));
        PublicKey publicKey = PemUtil.readPemPublicKey(ResourceUtil.getStream("D:\\SystemDocument\\Desktop\\1979263_jpom.keepbx.cn.pem"));

        RSA rsa = new RSA(privateKey, publicKey);
        String str = "你好,Hutool";//测试字符串

        String encryptStr = rsa.encryptBase64(str, KeyType.PublicKey);
        String decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey);
        System.out.println(encryptStr);
        System.out.println(decryptStr);
        System.out.println(str.equals(decryptStr));
    }
 
Example #10
Source File: UserController.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Log("修改邮箱")
@ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}")
public ResponseEntity<Object> updateEmail(@PathVariable String code,@RequestBody User user){
    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String password = new String(rsa.decrypt(user.getPassword(), KeyType.PrivateKey));
    UserDTO userDto = userService.findByName(SecurityUtils.getCurrentUsername());
    if(!passwordEncoder.matches(password, userDto.getPassword())){
        throw new SkException("密码错误");
    }
    VerificationCode verificationCode = new VerificationCode(code, CommonConstant.RESET_MAIL,"email",user.getEmail());
    verificationCodeService.validated(verificationCode);
    userService.updateEmail(userDto.getUsername(),user.getEmail());
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #11
Source File: AuthController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Log("用户登录")
@ApiOperation("登录授权")
@AnonymousAccess
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request){
    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey));
    // 查询验证码
    String code = (String) redisUtils.get(authUser.getUuid());
    // 清除验证码
    redisUtils.del(authUser.getUuid());
    if (StringUtils.isBlank(code)) {
        throw new BadRequestException("验证码不存在或已过期");
    }
    if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
        throw new BadRequestException("验证码错误");
    }
    UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);

    Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    // 生成令牌
    String token = tokenProvider.createToken(authentication);
    final JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
    // 保存在线信息
    onlineUserService.save(jwtUser, token, request);
    // 返回 token 与 用户信息
    Map<String,Object> authInfo = new HashMap<String,Object>(2){{
        put("token", properties.getTokenStartWith() + token);
        put("user", jwtUser);
    }};
    if(singleLogin){
        //踢掉之前已经登录的token
        onlineUserService.checkLoginOnUser(authUser.getUsername(),token);
    }
    return ResponseEntity.ok(authInfo);
}
 
Example #12
Source File: SecureSingleton.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 1. 将URI转义内容进行解码<br>
 * 2. 将RSA分段加密内容,进行分段解密
 * 
 * @param messageBody URI转义后的消息体
 * @return 解密后的JSON
 */
public static JSONObject rsaUriDecodingAndDecrypt(String messageBody) {
	String content = URIUtils.decode(messageBody);
	String jsonString = getRSA().decryptStrFromBcd(content, KeyType.PrivateKey);
	JSONObject json = null;
	try {
		json = JSONObject.parseObject(jsonString);
	}catch (Exception e) {
		throw new ConvertException(e.getMessage());
	}
	
	return json;
}
 
Example #13
Source File: CryptoExample.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@GetMapping("/secure")
public Result<?> secure() {
	// AES加密
	AES aes = SecureSingleton.getAES();
	aes.encryptBase64("");
	aes.decryptStr("");
	
	// RSA加密-公钥加密,私有解密
	RSA rsa = SecureSingleton.getRSA();
	rsa.encryptBcd("", KeyType.PublicKey);
	rsa.decryptStrFromBcd("", KeyType.PrivateKey);
	return ResultInfo.success();
}
 
Example #14
Source File: CryptoExample.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@GetMapping("/secure")
public Result<?> secure() {
	// AES加密
	AES aes = SecureSingleton.getAES();
	aes.encryptBase64("");
	aes.decryptStr("");
	
	// RSA加密-公钥加密,私有解密
	RSA rsa = SecureSingleton.getRSA();
	rsa.encryptBcd("", KeyType.PublicKey);
	rsa.decryptStrFromBcd("", KeyType.PrivateKey);
	return ResultInfo.success();
}
 
Example #15
Source File: AuthServiceImpl.java    From netty-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkValid(String username, String password) {
    if (StringUtils.isEmpty(username)){
        return false;
    }
    if (StringUtils.isEmpty(password)){
        return false;
    }
    RSA rsa = new RSA(privateKey,null);
    String value = rsa.encryptBcd(username, KeyType.PrivateKey);
    return value.equals(password) ? true : false;
}
 
Example #16
Source File: AuthController.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Log("用户登录")
@ApiOperation("登录授权")
@AnonymousAccess
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDTO authUser, HttpServletRequest request) {
    // 密码解密
    RSA rsa = new RSA(privateKey, null);
    String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey));
    // 查询验证码
    String code = (String) redisUtils.get(authUser.getUuid());
    // 清除验证码
    redisUtils.del(authUser.getUuid());
    if (StringUtils.isBlank(code)) {
        throw new SkException("验证码不存在或已过期");
    }
    if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
        throw new SkException("验证码错误");
    }
    UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);

    Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    // 生成令牌
    String token = tokenProvider.createToken(authentication);
    final JwtUserDTO jwtUserDto = (JwtUserDTO) authentication.getPrincipal();
    // 保存在线信息
    onlineUserService.save(jwtUserDto, token, request);
    // 返回 token 与 用户信息
    Map<String, Object> authInfo = new HashMap<String, Object>(4) {{
        put("token", properties.getTokenStartWith() + token);
        put("user", jwtUserDto);
    }};
    if (singleLogin) {
        //踢掉之前已经登录的token
        onlineUserService.checkLoginOnUser(authUser.getUsername(), token);
    }
    return ResponseEntity.ok(authInfo);
}
 
Example #17
Source File: AccoutResource.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Log("修改邮箱")
@ApiOperation("修改邮箱")
@PostMapping(value = "/account/change-email/{code}")
public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody UserEmailDto userEmailDto) {
	// 密码解密
	RSA rsa = new RSA(applicationProperties.getRsa().getPrivateKey(), applicationProperties.getRsa().getPublicKey());
	String password = new String(rsa.decrypt(userEmailDto.getPassword(), KeyType.PrivateKey));
	userEmailDto.setPassword(password);
	emailService.validated(CommonConstants.EMAIL_RESET_EMAIL_CODE + userEmailDto.getEmail(), code);
	userService.updateEmail(SecurityUtil.getUser().getUsername(), userEmailDto);
	return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #18
Source File: CertModel.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 解析证书
 *
 * @param key  zip里面文件
 * @param file 证书文件
 * @return 处理后的json
 */
public static JSONObject decodeCert(String file, String key) {
    if (file == null) {
        return null;
    }
    if (!FileUtil.exist(file)) {
        return null;
    }
    InputStream inputStream = null;
    try {
        inputStream = ResourceUtil.getStream(key);
        PrivateKey privateKey = PemUtil.readPemPrivateKey(inputStream);
        IoUtil.close(inputStream);
        inputStream = ResourceUtil.getStream(file);
        PublicKey publicKey = PemUtil.readPemPublicKey(inputStream);
        IoUtil.close(inputStream);
        RSA rsa = new RSA(privateKey, publicKey);
        String encryptStr = rsa.encryptBase64(KEY, KeyType.PublicKey);
        String decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey);
        if (!KEY.equals(decryptStr)) {
            throw new JpomRuntimeException("证书和私钥证书不匹配");
        }
    } finally {
        IoUtil.close(inputStream);
    }
    try {
        inputStream = ResourceUtil.getStream(file);
        // 创建证书对象
        X509Certificate oCert = (X509Certificate) KeyUtil.readX509Certificate(inputStream);
        //到期时间
        Date expirationTime = oCert.getNotAfter();
        //生效日期
        Date effectiveTime = oCert.getNotBefore();
        //域名
        String name = oCert.getSubjectDN().getName();
        int i = name.indexOf("=");
        String domain = name.substring(i + 1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expirationTime", expirationTime.getTime());
        jsonObject.put("effectiveTime", effectiveTime.getTime());
        jsonObject.put("domain", domain);
        jsonObject.put("pemPath", file);
        jsonObject.put("keyPath", key);
        return jsonObject;
    } catch (Exception e) {
        DefaultSystemLog.getLog().error(e.getMessage(), e);
    } finally {
        IoUtil.close(inputStream);
    }
    return null;
}
 
Example #19
Source File: AuthApiController.java    From netty-learning-example with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/{username}/auth",method = RequestMethod.GET,produces = "application/json")
public String getPwd(@PathVariable("username") String username){
    RSAPrivateKey privateKey = IoUtil.readObj(AuthApiController.class.getClassLoader().getResourceAsStream("keystore/auth-private.key"));
    RSA rsa = new RSA(privateKey, null);
    return rsa.encryptBcd(username, KeyType.PrivateKey);
}