Java Code Examples for org.springframework.util.Base64Utils#decodeFromString()

The following examples show how to use org.springframework.util.Base64Utils#decodeFromString() . 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: LoginFilter.java    From demo-project with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    if (httpServletRequest.getRequestURI().startsWith("/static")) {
        UserContextHolder.remove();
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    String token = httpServletRequest.getParameter("token");
    if (this.check(token)) {
        //token和用户id保存到userContextholder
        String str = new String(Base64Utils.decodeFromString(token.split("\\.")[1]));
        UserContext context = new UserContext(JSON.parseObject(str).getString("name"), token);
        UserContextHolder.set(context);
        filterChain.doFilter(servletRequest, servletResponse);
    } else {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(new ReturnEntity(-1, "未登录", null)));
    }
}
 
Example 2
Source File: Certificate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the certificate as {@link X509Certificate}. Only supported if certificate
 * is DER-encoded.
 * @return the {@link X509Certificate}.
 */
public X509Certificate getX509Certificate() {

	try {
		byte[] bytes = Base64Utils.decodeFromString(getCertificate());
		return KeystoreUtil.getCertificate(bytes);
	}
	catch (CertificateException e) {
		throw new VaultException("Cannot create Certificate from certificate", e);
	}
}
 
Example 3
Source File: FileUploadController.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
@PostMapping("/upload3")
@ResponseBody
public void upload2(String base64) throws IOException {
    // TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,)
    final File tempFile = new File("F:\\app\\chapter16\\test.jpg");
    // TODO 防止有的传了 data:image/png;base64, 有的没传的情况
    String[] d = base64.split("base64,");
    final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
    FileCopyUtils.copy(bytes, tempFile);

}
 
Example 4
Source File: AddMailingImageEndpoint.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
  protected Object invokeInternal(Object o) throws Exception {
      AddMailingImageRequest req = (AddMailingImageRequest) o;
      AddMailingImageResponse res = objectFactory.createAddMailingImageResponse();

      validateParameters(req);

      MailingComponent component = new MailingComponentImpl();
      component.setMailingID(req.getMailingID());
      component.setCompanyID(Utils.getUserCompany());
      component.setType(MailingComponent.TYPE_HOSTED_IMAGE);
      component.setDescription(req.getDescription());
      
      byte[] fileData = Base64Utils.decodeFromString(req.getContent());
if (fileData.length > configService.getIntegerValue(ConfigValue.MaximumUploadImageSize)) {
	throw new ComponentMaximumSizeExceededException();
}

      component.setComponentName(req.getFileName());
      component.setBinaryBlock(fileData, mimeTypeService.getMimetypeForFile(req.getFileName()));

      int urlId = saveTrackableLink(req);
      component.setUrlID(urlId);

      int imageComponentId = componentService.addMailingComponent(component);

      res.setID(imageComponentId);
      return res;
  }
 
Example 5
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static VaultDecryptionResult getDecryptionResult(Map<String, String> data, Ciphertext ciphertext) {

		if (StringUtils.hasText(data.get("error"))) {
			return new VaultDecryptionResult(new VaultException(data.get("error")));
		}

		if (StringUtils.hasText(data.get("plaintext"))) {

			byte[] plaintext = Base64Utils.decodeFromString(data.get("plaintext"));
			return new VaultDecryptionResult(Plaintext.of(plaintext).with(ciphertext.getContext()));
		}

		return new VaultDecryptionResult(Plaintext.empty().with(ciphertext.getContext()));
	}
 
Example 6
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] decrypt(String keyName, String ciphertext, VaultTransitContext transitContext) {

	Assert.hasText(keyName, "Key name must not be empty");
	Assert.hasText(ciphertext, "Ciphertext must not be empty");
	Assert.notNull(transitContext, "VaultTransitContext must not be null");

	Map<String, String> request = new LinkedHashMap<>();

	request.put("ciphertext", ciphertext);

	applyTransitOptions(transitContext, request);

	String plaintext = (String) this.vaultOperations
			.write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext");

	return Base64Utils.decodeFromString(plaintext);
}
 
Example 7
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传base64处理后的图片
 *
 * @param base64Data
 * @return
 */
@RequestMapping(value = "/upload/oss/base64", method = RequestMethod.POST)
@ResponseBody
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        log.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception(sourceService.getMessage("NOT_FIND_FILE"));
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception(sourceService.getMessage("DATA_ILLEGAL"));
            }
        }
        log.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
            mr.setData(uri);
            mr.setMessage(sourceService.getMessage("UPLOAD_SUCCESS"));
            log.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            log.info(ee.getMessage());
            throw new Exception(sourceService.getMessage("FAILED_TO_WRITE"));
        }
    } catch (Exception e) {
        log.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage(e.getMessage());
    }
    return result;
}
 
Example 8
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequiresPermissions("common:upload:oss:base64")
@RequestMapping(value = "/oss/base64", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "base64上传oss")
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        logger.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";

        logger.debug("对数据进行判断");
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception("上传失败,上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败,数据不合法");
            }
        }

        logger.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, "上传成功");
            mr.setData(uri);
            logger.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            throw new Exception("上传失败,写入文件失败," + ee.getMessage());
        }
    } catch (Exception e) {
        logger.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage("上传失败," + e.getMessage());
    }
    return result;
}
 
Example 9
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 10
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 11
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 12
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 13
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 14
Source File: TokenController.java    From mini-platform with MIT License 4 votes vote down vote up
/**
     * 获取 AccessToken,暂不支持scope
     *
     * @param
     * @param grantType
     * @param username 当grant_type=password时,username、password有效
     * @param password
     * @param refreshToken 当grant_type=refresh_token时,该参数有效
     * @return
     */
    @PostMapping()
    public ResponseEntity<AccessToken> postToken(
//            @RequestHeader("client_id") String clientId,
//            @RequestHeader("client_secret") String clientSecret,
            HttpServletRequest request,
            @RequestParam(name = "grant_type") String grantType,
            @RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String password,
            @RequestParam(name = "refresh_token", defaultValue = "") String refreshToken) {

        // client_id & client_secret可以通过参数传递,也可以通过HTTP Header的Authorization传递
        String clientId = request.getParameter("client_id");
        String clientSecret = request.getParameter("client_secret");

        if (StringUtils.isEmpty(clientId)) {
            String authorization = request.getHeader("Authorization");
            if (authorization == null || !authorization.startsWith("Basic ")) {
                throw new BusinessException(ErrorMessage.TOKEN_AUTHORIZATION_ERROR);
            }

            try {
                String authDecode = new String(Base64Utils.decodeFromString(authorization.substring(6)));
                String[] accounts = authDecode.split(":");
                clientId = accounts[0];
                //Password模式时,clientId必填,clientSecret是可选的。
                if (accounts.length > 1) {
                    clientSecret = accounts[1];
                }
            } catch (Exception e) {
                throw new BusinessException(ErrorMessage.TOKEN_AUTHORIZATION_ERROR);
            }
        }

        String accessIp = NetUtils.getIpAddress(request);

        AccessToken accessToken = accessTokenService.createAccessToken(accessIp, clientId, clientSecret, grantType, username, password, refreshToken);
        if (accessToken != null) {
            return ResponseEntity.ok(accessToken);
        }
        return ResponseEntity.badRequest().build();
    }
 
Example 15
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String unlock(String securityCode) {
    byte[] bytes = Base64Utils.decodeFromString(securityCode);
    return new String(bytes);
}
 
Example 16
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传base64处理后的图片
 *
 * @param base64Data
 * @return
 */
@RequestMapping(value = "/upload/oss/base64", method = RequestMethod.POST)
@ResponseBody
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        log.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception(sourceService.getMessage("NOT_FIND_FILE"));
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception(sourceService.getMessage("DATA_ILLEGAL"));
            }
        }
        log.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
            mr.setData(uri);
            mr.setMessage(sourceService.getMessage("UPLOAD_SUCCESS"));
            log.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            log.info(ee.getMessage());
            throw new Exception(sourceService.getMessage("FAILED_TO_WRITE"));
        }
    } catch (Exception e) {
        log.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage(e.getMessage());
    }
    return result;
}
 
Example 17
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequiresPermissions("common:upload:oss:base64")
@RequestMapping(value = "/oss/base64", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "base64上传oss")
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        logger.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";

        logger.debug("对数据进行判断");
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception("上传失败,上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败,数据不合法");
            }
        }

        logger.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, "上传成功");
            mr.setData(uri);
            logger.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            throw new Exception("上传失败,写入文件失败," + ee.getMessage());
        }
    } catch (Exception e) {
        logger.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage("上传失败," + e.getMessage());
    }
    return result;
}
 
Example 18
Source File: GsonBuilderUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) {
	return Base64Utils.decodeFromString(json.getAsString());
}
 
Example 19
Source File: GsonBuilderUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) {
	return Base64Utils.decodeFromString(json.getAsString());
}
 
Example 20
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Override
public String decrypt(String keyName, String ciphertext) {

	Assert.hasText(keyName, "Key name must not be empty");
	Assert.hasText(ciphertext, "Ciphertext must not be empty");

	Map<String, String> request = new LinkedHashMap<>();

	request.put("ciphertext", ciphertext);

	String plaintext = (String) this.vaultOperations
			.write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext");

	return new String(Base64Utils.decodeFromString(plaintext));
}