org.springframework.util.Base64Utils Java Examples
The following examples show how to use
org.springframework.util.Base64Utils.
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: Base64MultipartFile.java From bird-java with MIT License | 6 votes |
/** * 根据 * * @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 #2
Source File: ProductResourceIntTest.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 6 votes |
@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 #3
Source File: DesCbcUtil.java From faster-framework-project with Apache License 2.0 | 6 votes |
/** * * @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 #4
Source File: DesCbcUtil.java From faster-framework-project with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: TokenService.java From Learning-Path-Spring-5-End-to-End-Programming with MIT License | 6 votes |
@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: GenerateKeyImpl.java From julongchain with Apache License 2.0 | 6 votes |
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 #7
Source File: ProductResourceIntTest.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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 #8
Source File: DefaultArangoConverter.java From spring-data with Apache License 2.0 | 6 votes |
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 #9
Source File: AwsIamAuthentication.java From spring-vault with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: MessageServiceImpl.java From sctalk with Apache License 2.0 | 6 votes |
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 #11
Source File: HttpIT.java From vertx-spring-boot with Apache License 2.0 | 6 votes |
@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 #12
Source File: Base64Test.java From mblog with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: ProductResourceIntTest.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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 #14
Source File: TokenService.java From Spring-5.0-By-Example with MIT License | 6 votes |
@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 #15
Source File: ConfigServicePropertySourceLocator.java From spring-cloud-config with Apache License 2.0 | 6 votes |
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 #16
Source File: HttpBasicAuth.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) { if (username == null && password == null) { return; } String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); }
Example #17
Source File: HttpBasicAuth.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) { if (username == null && password == null) { return; } String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); }
Example #18
Source File: ArticleServiceImpl.java From NoteBlog with MIT License | 5 votes |
@Override public Map<String, Object> upload(String type, String base64Data) { log.info("上传 [{}] 类型文件", type); String path = type.contains("image/") ? FileType.IMAGE : FileType.FILE; String ext = type.split("/")[1].replace(";", ""); String fileName = LangUtils.random.uuidCool().concat(".").concat(ext); return upload(path, fileName, () -> Base64Utils.decodeFromString(base64Data), type); }
Example #19
Source File: VaultTransitTemplate.java From spring-vault with Apache License 2.0 | 5 votes |
private static void applyTransitOptions(VaultTransitContext context, Map<String, String> request) { if (!ObjectUtils.isEmpty(context.getContext())) { request.put("context", Base64Utils.encodeToString(context.getContext())); } if (!ObjectUtils.isEmpty(context.getNonce())) { request.put("nonce", Base64Utils.encodeToString(context.getNonce())); } }
Example #20
Source File: GithubClient.java From spring-boot-samples with Apache License 2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { if (StringUtils.hasText(this.token)) { byte[] basicAuthValue = this.token.getBytes(StandardCharsets.UTF_8); httpRequest.getHeaders().set(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(basicAuthValue)); } return clientHttpRequestExecution.execute(httpRequest, bytes); }
Example #21
Source File: HttpBasicAuth.java From tutorials with MIT License | 5 votes |
@Override public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) { if (username == null && password == null) { return; } String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); }
Example #22
Source File: BasicAuthorizationInterceptor.java From java-technology-stack with MIT License | 5 votes |
@Override public ClientHttpResponse intercept( HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { String token = Base64Utils.encodeToString( (this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8)); request.getHeaders().add("Authorization", "Basic " + token); return execution.execute(request, body); }
Example #23
Source File: MultiModuleConfigServicePropertySourceLocator.java From spring-cloud-formula with Apache License 2.0 | 5 votes |
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 #24
Source File: RSAUtils.java From danyuan-application with Apache License 2.0 | 5 votes |
/** * <P> * 私钥解密 * </p> * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, byte[] privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); 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 #25
Source File: Base64Test.java From xmanager with Apache License 2.0 | 5 votes |
/** * Shiro 记住密码采用的是AES加密,AES key length 需要是16位,该方法生成16位的key */ public static void main(String[] args) { String keyStr = "如梦技术"; byte[] keys = keyStr.getBytes(Charsets.UTF_8); System.out.println(Base64Utils.encodeToString(Arrays.copyOf(keys, 16))); }
Example #26
Source File: CgiBin.java From ds-server-PoC with MIT License | 5 votes |
/** * Announce message format is: [0x01, 0xF4, 0x02, 0x00, 0x00, 0x01, 0x01, announce text, 0x00] */ @PostMapping("/login.spd") public String postRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { log.warn("cgi-bin"); final InputStream stream = getClass().getClassLoader().getResourceAsStream("announce.bin"); final byte[] bytes = IOUtils.toByteArray(stream); return Base64Utils.encodeToString(bytes) + "\n"; }
Example #27
Source File: Base64Test.java From MeetingFilm with Apache License 2.0 | 5 votes |
/** * Shiro 记住密码采用的是AES加密,AES key length 需要是16位,该方法生成16位的key */ public static void main(String[] args) { String keyStr = "guns"; byte[] keys; try { keys = keyStr.getBytes("UTF-8"); System.out.println(Base64Utils.encodeToString(Arrays.copyOf(keys, 16))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
Example #28
Source File: FileUploadController.java From springboot-learning-experience with Apache License 2.0 | 5 votes |
@PostMapping("/upload3") @ResponseBody public void upload2(String base64) throws IOException { // TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,) final File tempFile = new File("/Users/Winterchen/Desktop/javatest/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 #29
Source File: AuthResolverIntegrationTest.java From tutorials with MIT License | 5 votes |
@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 #30
Source File: VaultTransitTemplate.java From spring-vault with Apache License 2.0 | 5 votes |
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())); }