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

The following examples show how to use org.springframework.util.Base64Utils#encodeToString() . 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: DesCbcUtil.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param plainText 普通文本
 * @param secretKey 密钥
 * @param iv 向量
 * @return 加密后的文本,失败返回null
 */
public static String encode(String plainText, String secretKey, String iv) {
    String result = null;
    try {
        DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
        Key desKey = secretKeyFactory.generateSecret(deSedeKeySpec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);
        byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
        result = Base64Utils.encodeToString(encryptData);
    } catch (Exception e) {
        log.error("DesCbcUtil encode error : {}", e);
    }
    return result;
}
 
Example 2
Source File: TokenService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token() {
  val authorizationHeader = Base64Utils.encodeToString((this.clientId + ":" + this.clientSecret).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example 3
Source File: HttpIT.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicAuth() {
    startServer(SessionController.class, AuthConfiguration.class);

    getWebTestClient()
        .get()
        .exchange()
        .expectStatus()
        .isUnauthorized();

    String authHash = Base64Utils.encodeToString("user:password".getBytes(StandardCharsets.UTF_8));

    getWebTestClient()
        .get()
        .header(HttpHeaders.AUTHORIZATION, "Basic " + authHash)
        .exchange()
        .expectStatus()
        .isOk()
        .expectBody(String.class)
        .value(not(isEmptyOrNullString()));
}
 
Example 4
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(@NonNull Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example 5
Source File: TokenService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString(( credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example 6
Source File: BasicAuthorizationInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	String token = Base64Utils.encodeToString((this.username + ":" + this.password).getBytes(UTF_8));
	request.getHeaders().add("Authorization", "Basic " + token);
	return execution.execute(request, body);
}
 
Example 7
Source File: RsaUtil.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 公钥加密
 *
 * @param base64PublicKey base64 公钥
 * @param data            待加密的内容
 * @return 加密后的内容
 */
@Nullable
public static String encryptToBase64(String base64PublicKey, @Nullable String data) {
	if (StringUtil.isBlank(data)) {
		return null;
	}
	return Base64Utils.encodeToString(encrypt(base64PublicKey, data.getBytes(Charsets.UTF_8)));
}
 
Example 8
Source File: ExpressService.java    From mall with MIT License 5 votes vote down vote up
/**
 * Sign签名生成
 *
 * @param content  内容
 * @param keyValue Appkey
 * @param charset  编码方式
 * @return DataSign签名
 */
private String encrypt(String content, String keyValue, String charset) {
    if (keyValue != null) {
        content = content + keyValue;
    }
    byte[] src = new byte[0];
    try {
        src = MD5(content, charset).getBytes(charset);
        return Base64Utils.encodeToString(src);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 9
Source File: ExpressService.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
/**
 * Sign签名生成
 *
 * @param content  内容
 * @param keyValue Appkey
 * @param charset  编码方式
 * @return DataSign签名
 */
private String encrypt(String content, String keyValue, String charset) {
    if (keyValue != null) {
        content = content + keyValue;
    }
    byte[] src;
    try {
        src = MD5(content, charset).getBytes(charset);
        return Base64Utils.encodeToString(src);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return null;
}
 
Example 10
Source File: LetsChatNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);
	// Let's Chat requiers the token as basic username, the password can be an
	// arbitrary string.
	String auth = Base64Utils
			.encodeToString(String.format("%s:%s", token, username).getBytes(StandardCharsets.UTF_8));
	headers.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth));
	return Mono.fromRunnable(() -> restTemplate.exchange(createUrl(), HttpMethod.POST,
			new HttpEntity<>(createMessage(event, instance), headers), Void.class));
}
 
Example 11
Source File: ServiceMetadata.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
private String base64EncodeImageData(String filename) {
	String formattedImageData = null;
	ClassPathResource resource = new ClassPathResource(filename);
	try (InputStream stream = resource.getInputStream()) {
		byte[] imageBytes = StreamUtils.copyToByteArray(stream);
		String imageData = Base64Utils.encodeToString(imageBytes);
		formattedImageData = String.format(IMAGE_DATA_FORMAT, imageData);
	}
	catch (IOException e) {
		LOG.warn("Error converting image file to byte array", e);
	}
	return formattedImageData;
}
 
Example 12
Source File: GatewayEventRestEndpointTest.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Test
  public void shouldPubToKonkerPlatform() throws Exception {
      HttpHeaders headers = new HttpHeaders();
      String encodedCredentials = Base64Utils
              .encodeToString(format("{0}:{1}", rabbitMQConfig.getUsername(), rabbitMQConfig.getPassword()).getBytes());
      headers.add("Authorization", format("Basic {0}", encodedCredentials));
      HttpEntity<String> entity = new HttpEntity(
              null,
              headers
      );

  	SecurityContext context = SecurityContextHolder.getContext();
      Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null);
      context.setAuthentication(auth);

      when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883"))
      	.thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok()
      			.withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build());
      when(jsonParsingService.isValid(json)).thenReturn(true);
      when(restTemplate.exchange(
              format("http://{0}:{1}/{2}", rabbitMQConfig.getHostname(), rabbitMQConfig.getApiPort(), "api/healthchecks/node"),
              HttpMethod.GET,
              entity,
              String.class)).thenReturn(new ResponseEntity<String>(HttpStatus.OK));


getMockMvc().perform(
              post("/gateway/pub")
              	.flashAttr("principal", gateway)
                  .contentType(MediaType.APPLICATION_JSON)
                  .content(json))
              	.andExpect(status().isOk())
              	.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"200\",\"message\":\"OK\"}")));

  }
 
Example 13
Source File: Base64SecurityAction.java    From MeetingFilm with Apache License 2.0 4 votes vote down vote up
@Override
public String doAction(String beProtected) {
    return Base64Utils.encodeToString(beProtected.getBytes());
}
 
Example 14
Source File: GsonBuilderUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
	return new JsonPrimitive(Base64Utils.encodeToString(src));
}
 
Example 15
Source File: ByteArrayBase64PropertyEditor.java    From raptor with Apache License 2.0 4 votes vote down vote up
@Override
public String getAsText() {
    byte[] value = (byte[]) getValue();
    return (value != null ? Base64Utils.encodeToString(value) : "");
}
 
Example 16
Source File: BasicAuthHttpHeaderProvider.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
protected String encode(String username, String password) {
	String token = Base64Utils.encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
	return "Basic " + token;
}
 
Example 17
Source File: BaseControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
private String encode(String json) {
	return Base64Utils.encodeToString(json.getBytes());
}
 
Example 18
Source File: BasicAuthHttpHeaderProvider.java    From Moss with Apache License 2.0 4 votes vote down vote up
protected String encode(String username, String password) {
    String token = Base64Utils.encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
    return "Basic " + token;
}
 
Example 19
Source File: GsonBuilderUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
	return new JsonPrimitive(Base64Utils.encodeToString(src));
}
 
Example 20
Source File: RsaUtil.java    From mica with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * 得到密钥字符串(经过base64编码)
 *
 * @param key key
 * @return base 64 编码后的 key
 */
public static String getKeyString(Key key) {
	return Base64Utils.encodeToString(key.getEncoded());
}