Java Code Examples for org.springframework.util.Base64Utils

The following examples show how to use org.springframework.util.Base64Utils. These examples are extracted from open source projects. 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 Project: mblog   Source File: Base64Test.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws UnsupportedEncodingException {
    byte[] keys = "mtons".getBytes("UTF-8");
    System.out.println(Base64Utils.encodeToString(Arrays.copyOf(keys, 16)));

    String src = "/static/";
    if (StringUtils.isNoneBlank(src) && src.length() > 1) {
        if (src.startsWith("/")) {
            src = src.substring(1);
        }

        if (!src.endsWith("/")) {
            src = src + "/";
        }
    }
    System.out.println(src);

    System.out.println("sg[hide]test[/hide]<asf>fsd</sdf>".replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", "$1"));
}
 
Example 2
private void addAuthorizationToken(ConfigClientProperties configClientProperties,
		HttpHeaders httpHeaders, String username, String password) {
	String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);

	if (password != null && authorization != null) {
		throw new IllegalStateException(
				"You must set either 'password' or 'authorization'");
	}

	if (password != null) {
		byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
		httpHeaders.add("Authorization", "Basic " + new String(token));
	}
	else if (authorization != null) {
		httpHeaders.add("Authorization", authorization);
	}

}
 
Example 3
Source Project: bird-java   Source File: Base64MultipartFile.java    License: MIT License 6 votes vote down vote up
/**
 * 根据
 *
 * @param base64 base64文件流
 * @return
 */
public static Base64MultipartFile init(String base64) {
    if (StringUtils.isBlank(base64) || !base64.contains(DELIMITER)) {
        LOGGER.warn("base64字符串格式错误");
        return null;
    }

    String[] arr = base64.split(",");
    if (arr.length != 2) {
        LOGGER.warn("base64字符串格式错误");
        return null;
    }

    String header = arr[0];
    byte[] content = Base64Utils.decodeFromString(arr[1]);

    return new Base64MultipartFile(header, content);
}
 
Example 4
Source Project: Spring-5.0-By-Example   Source File: TokenService.java    License: 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 5
@Test
@Transactional
public void getAllProducts() throws Exception {
    // Initialize the database
    productRepository.saveAndFlush(product);

    // Get all the productList
    restProductMockMvc.perform(get("/api/products?sort=id,desc"))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.[*].id").value(hasItem(product.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
        .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
        .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue())))
        .andExpect(jsonPath("$.[*].size").value(hasItem(DEFAULT_SIZE.toString())))
        .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE)))
        .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE))));
}
 
Example 6
Source Project: vertx-spring-boot   Source File: HttpIT.java    License: 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 7
Source Project: sctalk   Source File: MessageServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public List<MessageEntity> findGroupMessageList(List<? extends IMGroupMessageEntity> messageList) {
    List<MessageEntity> resultList = new ArrayList<>();
    for (IMGroupMessageEntity message : messageList) {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setId(message.getId());
        messageEntity.setMsgId(message.getMsgId());
        if (message.getType() == IMBaseDefine.MsgType.MSG_TYPE_GROUP_AUDIO_VALUE) {
            // 语音Base64
            byte[] audioData = audioInternalService.readAudioInfo(Long.valueOf(message.getContent()));
            messageEntity.setContent(Base64Utils.encodeToString(audioData));
        } else {
            messageEntity.setContent(message.getContent());
        }
        messageEntity.setFromId(message.getUserId());
        messageEntity.setCreated(message.getCreated());
        messageEntity.setStatus(message.getStatus());
        messageEntity.setMsgType(message.getType());

        resultList.add(messageEntity);
    }
    return resultList;
}
 
Example 8
Source Project: spring-vault   Source File: AwsIamAuthentication.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the request body to perform a Vault login using the AWS-IAM authentication
 * method.
 * @param options must not be {@literal null}.
 * @return the map containing body key-value pairs.
 */
private static Map<String, String> createRequestBody(AwsIamAuthenticationOptions options,
		AWSCredentials credentials) {

	Map<String, String> login = new HashMap<>();

	login.put("iam_http_request_method", "POST");
	login.put("iam_request_url", Base64Utils.encodeToString(options.getEndpointUri().toString().getBytes()));
	login.put("iam_request_body", REQUEST_BODY_BASE64_ENCODED);

	String headerJson = getSignedHeaders(options, credentials);

	login.put("iam_request_headers", Base64Utils.encodeToString(headerJson.getBytes()));

	if (!StringUtils.isEmpty(options.getRole())) {
		login.put("role", options.getRole());
	}
	return login;
}
 
Example 9
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeArray(
	final String attribute,
	final Object source,
	final VPackBuilder sink,
	final TypeInformation<?> definedType) {

	if (byte[].class.equals(source.getClass())) {
		sink.add(attribute, Base64Utils.encodeToString((byte[]) source));
	}

	else {
		sink.add(attribute, ValueType.ARRAY);
		for (int i = 0; i < Array.getLength(source); ++i) {
			final Object element = Array.get(source, i);
			writeInternal(null, element, sink, getNonNullComponentType(definedType));
		}
		sink.close();
	}
}
 
Example 10
@Test
public void searchProduct() throws Exception {
    // Initialize the database
    productRepository.save(product);
    when(mockProductSearchRepository.search(queryStringQuery("id:" + product.getId()), PageRequest.of(0, 20)))
        .thenReturn(new PageImpl<>(Collections.singletonList(product), PageRequest.of(0, 1), 1));
    // Search the product
    restProductMockMvc.perform(get("/api/_search/products?query=id:" + product.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.[*].id").value(hasItem(product.getId())))
        .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString())))
        .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue())))
        .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE)))
        .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE))));
}
 
Example 11
@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 12
Source Project: faster-framework-project   Source File: DesCbcUtil.java    License: 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 13
Source Project: faster-framework-project   Source File: DesCbcUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  3DES解密
 * @param encryptText 加密文本
 * @param secretKey 密钥
 * @param iv 向量
 * @return 解密后明文,失败返回null
 */
public static String decode(String encryptText, String secretKey, String iv) {
    String result = null;
    try {
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
        Key desKey = secretKeyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, desKey, ips);
        byte[] decryptData = cipher.doFinal(Base64Utils.decodeFromString(encryptText));
        result = new String(decryptData, encoding);
    } catch (Exception e) {
        log.error("DesCbcUtil decode error : {}", e.getMessage());
    }
    return result;
}
 
Example 14
Source Project: julongchain   Source File: GenerateKeyImpl.java    License: Apache License 2.0 6 votes vote down vote up
public PrivateKey LoadPrivateKeyAsPEM(String path,  String algorithm)
        throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {

    File file = new File(path);
    InputStream inputStream = new FileInputStream(file);//文件内容的字节流
    InputStreamReader inputStreamReader= new InputStreamReader(inputStream); //得到文件的字符流
    BufferedReader bufferedReader=new BufferedReader(inputStreamReader); //放入读取缓冲区
    String readd="";
    StringBuffer stringBuffer=new StringBuffer();
    while ((readd=bufferedReader.readLine())!=null) {
        stringBuffer.append(readd);
    }
    inputStream.close();
    String content=stringBuffer.toString();

    String privateKeyPEM = content.replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("-----END PRIVATE KEY-----", "").replace("\n", "");
    byte[] asBytes = Base64Utils.decode(privateKeyPEM.getBytes());
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(asBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    return keyFactory.generatePrivate(spec);
}
 
Example 15
@Test
@Transactional
public void getProduct() throws Exception {
    // Initialize the database
    productRepository.saveAndFlush(product);

    // Get the product
    restProductMockMvc.perform(get("/api/products/{id}", product.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.id").value(product.getId().intValue()))
        .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
        .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
        .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.intValue()))
        .andExpect(jsonPath("$.size").value(DEFAULT_SIZE.toString()))
        .andExpect(jsonPath("$.imageContentType").value(DEFAULT_IMAGE_CONTENT_TYPE))
        .andExpect(jsonPath("$.image").value(Base64Utils.encodeToString(DEFAULT_IMAGE)));
}
 
Example 16
@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 17
Source Project: tutorials   Source File: AuthResolverIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenEmployeeCredential_whenWelcomeCustomer_thenExpect401Status() throws Exception {
    this.mockMvc
      .perform(get("/customer/welcome")
        .header(
          "Authorization", "Basic " + Base64Utils.encodeToString("employee1:pass1".getBytes()))
      )
      .andExpect(status().isUnauthorized());
}
 
Example 18
Source Project: mica   Source File: RsaUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 得到公钥
 *
 * @param base64PubKey 密钥字符串(经过base64编码)
 * @return PublicKey
 */
public static PublicKey getPublicKey(String base64PubKey) {
	Objects.requireNonNull(base64PubKey, "base64 public key is null.");
	byte[] keyBytes = Base64Utils.decodeFromString(base64PubKey);
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
	try {
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
		return keyFactory.generatePublic(keySpec);
	} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 19
@Test
void authorizationHeaderIsSet() {
	downloadArchive("/starter.zip");
	assertThat(this.statsMockController.stats).as("No stat got generated").hasSize(1);
	StatsMockController.Content content = this.statsMockController.stats.get(0);

	String authorization = content.authorization;
	assertThat(authorization).as("Authorization header must be set").isNotNull();
	assertThat(authorization).startsWith("Basic ");
	String token = authorization.substring("Basic ".length(), authorization.length());
	String[] data = new String(Base64Utils.decodeFromString(token)).split(":");
	assertThat(data[0]).as("Wrong user from " + token).isEqualTo("test-user");
	assertThat(data[1]).as("Wrong password " + token).isEqualTo("test-password");
}
 
Example 20
Source Project: danyuan-application   Source File: RSAUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 用私钥对信息生成数字签名
 * </p>
 * @param data 已加密数据
 * @param privateKey 私钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
	byte[] keyBytes = Base64Utils.decode(privateKey);
	PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
	Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
	signature.initSign(privateK);
	signature.update(data);
	return Base64Utils.encode(signature.sign());
}
 
Example 21
Source Project: mica   Source File: RsaUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * base64 数据解密
 *
 * @param base64PrivateKey base64 私钥
 * @param base64Data       base64数据
 * @return 解密后的数据
 */
@Nullable
public static String decryptFromBase64(String base64PrivateKey, @Nullable String base64Data) {
	if (StringUtil.isBlank(base64Data)) {
		return null;
	}
	return new String(decrypt(base64PrivateKey, Base64Utils.decodeFromString(base64Data)), Charsets.UTF_8);
}
 
Example 22
Source Project: spring-vault   Source File: PcfAuthentication.java    License: Apache License 2.0 5 votes vote down vote up
private static String doSign(byte[] message, String instanceKeyPem) throws CryptoException {

		RSAPrivateKeySpec privateKey = PemObject.fromKey(instanceKeyPem).getRSAKeySpec();
		PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH);

		signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent()));
		signer.update(message, 0, message.length);

		byte[] signature = signer.generateSignature();
		return Base64Utils.encodeToUrlSafeString(signature);
	}
 
Example 23
Source Project: mica   Source File: RsaUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * base64 数据解密
 *
 * @param base64PublicKey base64 公钥
 * @param base64Data      base64数据
 * @return 解密后的数据
 */
@Nullable
public static String decryptByPublicKeyFromBase64(String base64PublicKey, @Nullable String base64Data) {
	if (StringUtil.isBlank(base64Data)) {
		return null;
	}
	return new String(decryptByPublicKeyFromBase64(base64PublicKey, Base64Utils.decodeFromString(base64Data)), Charsets.UTF_8);
}
 
Example 24
Source Project: fido2   Source File: MDSUrlService.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private MetadataStatement retrieveMetadataStatement(URI uri, String entryHash, MessageDigest digest, boolean forceUpdate) throws Exception {
    String filename = filenameFromURI(uri);
    String data = null;

    if (!forceUpdate) {
        data = storage.loadData(namespace, filename);
    }

    if (data == null) {
        String url = URLDecoder.decode(uri.toString(), StandardCharsets.UTF_8.name());
        url = addToken(url);
        url = url.replaceAll("#", "%23");
        URI realURI = URI.create(url);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(realURI, String.class);
        data = responseEntity.getBody();

        if(data == null){
            logger.severe("Null hash.");
            throw new Exception("Null hash");
        }

        String hash = Base64.getUrlEncoder().withoutPadding().encodeToString(digest.digest(data.getBytes()));
        if (!hash.equals(entryHash)) {
            logger.log(Level.SEVERE, "Bad hash. {0} != {1}  Skipping ", new Object[]{hash, entryHash});
            throw new Exception("Bad hash");
        }
        storage.saveData(namespace, filename, data);
    }

    String decoded;
    try {
        decoded = new String(Base64Utils.decodeFromUrlSafeString(data), StandardCharsets.UTF_8);
    } catch (Exception e) {
        // TODO: known bug: test server does not base64 this info
        decoded = data;
    }
    return objectMapper.readValue(decoded, MetadataStatement.class);

}
 
Example 25
Source Project: staffjoy   Source File: AssetLoader.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {

    // load image
    InputStream imageFileInputStream = this.getImageFile(IMAGE_FILE_PATH);
    byte[] encodedImage = IOUtils.toByteArray(imageFileInputStream);
    byte[] base64EncodedImage = Base64Utils.encode(encodedImage);
    imageBase64 = new String(base64EncodedImage);

    // load favicon
    InputStream faviconFileInputStream = this.getImageFile(FAVICON_FILE_PATH);
    faviconBytes = IOUtils.toByteArray(faviconFileInputStream);
}
 
Example 26
Source Project: danyuan-application   Source File: RSAUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 公钥解密
 * </p>
 * @param encryptedData 已加密数据
 * @param publicKey 公钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, byte[] publicKey) throws Exception {
	byte[] keyBytes = Base64Utils.decode(publicKey);
	X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	Key publicK = keyFactory.generatePublic(x509KeySpec);
	Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
	cipher.init(Cipher.DECRYPT_MODE, publicK);
	int inputLen = encryptedData.length;
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	int offSet = 0;
	byte[] cache;
	int i = 0;
	// 对数据分段解密
	while (inputLen - offSet > 0) {
		if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
			cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
		} else {
			cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
		}
		out.write(cache, 0, cache.length);
		i++;
		offSet = i * MAX_DECRYPT_BLOCK;
	}
	byte[] decryptedData = out.toByteArray();
	out.close();
	return decryptedData;
}
 
Example 27
Source Project: spring-vault   Source File: Certificate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the issuing CA certificate as {@link X509Certificate}. Only supported if
 * certificate is DER-encoded.
 * @return the issuing CA {@link X509Certificate}.
 */
public X509Certificate getX509IssuerCertificate() {

	try {
		byte[] bytes = Base64Utils.decodeFromString(getIssuingCaCertificate());
		return KeystoreUtil.getCertificate(bytes);
	}
	catch (CertificateException e) {
		throw new VaultException("Cannot create Certificate from issuing CA certificate", e);
	}
}
 
Example 28
Source Project: spring-boot-admin   Source File: LetsChatNotifier.java    License: 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 29
@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 30
/**
 * Generates a random 32 character token to be used in URLs.
 * 
 * @return a token.
 */
public static String getRandomUrlToken()
{
    SecureRandom sr = new SecureRandom();
    byte[] tokenBytes = new byte[ URL_RANDOM_TOKEN_LENGTH ];
    sr.nextBytes( tokenBytes );

    return Base64Utils.encodeToUrlSafeString( tokenBytes );
}