當前位置: 首頁>>代碼示例>>Java>>正文


Java Base64Utils.encodeToString方法代碼示例

本文整理匯總了Java中org.springframework.util.Base64Utils.encodeToString方法的典型用法代碼示例。如果您正苦於以下問題:Java Base64Utils.encodeToString方法的具體用法?Java Base64Utils.encodeToString怎麽用?Java Base64Utils.encodeToString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.util.Base64Utils的用法示例。


在下文中一共展示了Base64Utils.encodeToString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testLoginGood

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
@Test
public void testLoginGood() throws Exception {
    final List<Role> roles = Arrays.asList(Role.USER);
    final String username = "username";
    final String password = "password";
    final String s = Base64Utils.encodeToString((username + ":" + password).getBytes());

    when(authenticationService.login(eq(username), eq(password))).thenReturn(new AuthorizationInfo("id", "jwt token", roles));

    mockMvc.perform(post(PATH).header(HttpHeaders.AUTHORIZATION, "Basic " + s))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.id", is(equalTo("id"))))
            .andExpect(jsonPath("$.token", is(equalTo("jwt token"))))
            .andExpect(jsonPath("$.roles", hasSize(1)))
            .andExpect(jsonPath("$.roles[0]", is(equalTo("USER"))));
}
 
開發者ID:nus-ncl,項目名稱:services-in-one,代碼行數:18,代碼來源:AuthenticationControllerTest.java

示例2: testLoginHandlerSuccess

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
@Test
public void testLoginHandlerSuccess() throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
	register.unregister("sample");
	List<LSPayload> payloads = new LinkedList<>();
	DefaultLSSession.createSession("sample");
	WebSocket socket = new MockWebSocket();
	LoginHandler handler = new LoginHandler(userDB, register);
	byte[] macKey = TestUtils.generateMACKey();
	LSRequest req = new LSRequest("sample", new HashMap<>(), new Date(), LSRequest.LS_LOGIN,
			Base64Utils.encodeToString(macKey), socket);
	req.getAttributes().put("signature",
			AuthenticationUtils.INSTANCE.signMessage(req.getData(), req.getTimeStamp(), testKey.getPrivate()));
	LSResponse resp = handler.handleRequest(req, payloads);

	Assert.assertEquals(LSResponse.SUCCESS, resp.getStatus());
	Assert.assertNotEquals(null, register.getSocket("sample"));
	Assert.assertArrayEquals(macKey, DefaultLSSession.getSession("sample").getAttribute("macKey", byte[].class));
	Assert.assertEquals(0, payloads.size());
}
 
開發者ID:shilongdai,項目名稱:LSChatServer,代碼行數:20,代碼來源:LoginHandlerTest.java

示例3: sha256

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private String sha256(byte[] data) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data);
        return Base64Utils.encodeToString(md.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:10,代碼來源:MqttGatewaySecurityConfiguration.java

示例4: sha256

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private String sha256(byte[] data) {
  try {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(data);
    return Base64Utils.encodeToString(md.digest());
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 
開發者ID:osswangxining,項目名稱:iot-edge-greengrass,代碼行數:10,代碼來源:MqttGatewaySecurityConfiguration.java

示例5: setKeyPair

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
public void setKeyPair(KeyPair keyPair) {
	PrivateKey privateKey = keyPair.getPrivate();
	signer = new RSASSASigner(privateKey);
	RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	verifier = new RSASSAVerifier(publicKey);
	verifierKey = "-----BEGIN PUBLIC KEY-----\n"
			+ Base64Utils.encodeToString(publicKey.getEncoded())
			+ "\n-----END PUBLIC KEY-----";
}
 
開發者ID:making,項目名稱:spring-boot-actuator-dashboard,代碼行數:10,代碼來源:JwtTokenConverter.java

示例6: constructRequest

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private HttpEntity<MultiValueMap<String, String>> constructRequest(){
    String authorizationValue = Base64Utils.encodeToString((CLIENT_ID+":"+CLIENT_SECRET).getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic "+authorizationValue);
    headers.add("User-agent", userAgent);

    MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
    mvm.add("username",USERNAME);
    mvm.add("password",PASSWORD);
    mvm.add("grant_type", "password");

    return new HttpEntity<MultiValueMap<String, String>>(mvm, headers);
}
 
開發者ID:nicolasmanic,項目名稱:JRockets,代碼行數:15,代碼來源:Authentication.java

示例7: encryptByPublicKey

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
public static String encryptByPublicKey(String content, String publicKey, String charset) throws Exception {
	PublicKey publicK = getPublicKey(SIGN_ALGORITHM, publicKey);
	Cipher cipher = Cipher.getInstance(SIGN_ALGORITHM);
	cipher.init(Cipher.ENCRYPT_MODE, publicK);
	byte[] data = StringUtils.isEmpty(charset) ? content.getBytes() : content.getBytes(charset);
	int inputLen = data.length;
	try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 對數據分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		return Base64Utils.encodeToString(out.toByteArray());
	} catch (Exception e) {
		throw new CustomException("公鑰加密失敗", e);
	} finally {

	}
}
 
開發者ID:zhaoqilong3031,項目名稱:spring-cloud-samples,代碼行數:29,代碼來源:RSAUtils.java

示例8: encryptByPrivateKey

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
public static String encryptByPrivateKey(String content, String privateKey, String charset) throws Exception {
	PrivateKey privateK = getPrivate(SIGN_ALGORITHM, privateKey);
	Cipher cipher = Cipher.getInstance(SIGN_ALGORITHM);
	cipher.init(Cipher.ENCRYPT_MODE, privateK);
	byte[] data = StringUtils.isEmpty(charset) ? content.getBytes() : content.getBytes(charset);
	int inputLen = data.length;
	try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 對數據分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		return Base64Utils.encodeToString(out.toByteArray());
	} catch (Exception e) {
		throw new CustomException("私鑰加密失敗", e);
	} finally {

	}
}
 
開發者ID:zhaoqilong3031,項目名稱:spring-cloud-samples,代碼行數:29,代碼來源:RSAUtils.java

示例9: rsaSign

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
public static String rsaSign(String content, String privateKey, String charset) {
	try {
		PrivateKey priKey = getPrivate(SIGN_ALGORITHM, privateKey);
		java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
		signature.initSign(priKey);
		if (StringUtils.isEmpty(charset)) {
			signature.update(content.getBytes());
		} else {
			signature.update(content.getBytes(charset));
		}
		return Base64Utils.encodeToString(signature.sign());
	} catch (Exception e) {
		throw new CustomException("簽名失敗", e);
	}
}
 
開發者ID:zhaoqilong3031,項目名稱:spring-cloud-samples,代碼行數:16,代碼來源:RSAUtils.java

示例10: buildImage

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private Image buildImage(BarcodeFormat format,String data,int w,int h){
       try{
       	Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
           hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
           hints.put(EncodeHintType.MARGIN,0);
           if(format.equals(BarcodeFormat.QR_CODE)){
           	hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);            	
           }
           BitMatrix matrix = new MultiFormatWriter().encode(data,format, w, h,hints);
           int width = matrix.getWidth();  
           int height = matrix.getHeight();
           BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
           for (int x = 0; x < width; x++) {
           	for (int y = 0; y < height; y++) {
           		image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
           	}
           }
           ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
           ImageIO.write(image, "png", outputStream);
           byte[] bytes=outputStream.toByteArray();
           String base64Data=Base64Utils.encodeToString(bytes);
           IOUtils.closeQuietly(outputStream);
           return new Image(base64Data,w,h);
       }catch(Exception ex){
       	throw new ReportComputeException(ex);
       }
}
 
開發者ID:youseries,項目名稱:ureport,代碼行數:28,代碼來源:ZxingValueCompute.java

示例11: validateProxy

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
/**
	 * Validate a proxy over a given http page
	 * @param proxyAddress
	 * @param proxyPort
	 * @param testUrl the page to fetch (must include the third slash if just the host, like "http://somehost.com/"
	 * @param timeoutMillis
	 * @param username proxy basic authentication, or null when not needed
	 * @param password proxy basic authentication, or null when not needed
	 * @param userAgent to use when connecting (can be null for the default). E.g. "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"
	 * @return the milliseconds taken to fetch the page, or -1 in case of error/timeout
	 */
	public long validateProxy(String proxyAddress, int proxyPort, URL testUrl, int timeoutMillis, String username, String password, String userAgent) {
		long start = System.currentTimeMillis();
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
		try {
			URLConnection connection = testUrl.openConnection(proxy);
			connection.setReadTimeout(timeoutMillis);
			connection.setConnectTimeout(timeoutMillis);
			connection.setUseCaches(false);
			connection.getRequestProperty(password);
			if (userAgent!=null) {
				connection.setRequestProperty("User-Agent", userAgent);
			}
			if (username!=null && password !=null) {
				String auth = "Basic " + Base64Utils.encodeToString((username + ":" + password).getBytes());
				connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
				connection.setRequestProperty("Proxy-Authorization", auth);
			}
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null); 
			in.close();
			return System.currentTimeMillis()-start;
		} catch (IOException e) {
			log.debug("Failed to validate proxy {}", proxyAddress, e);
		}
		return -1;
//		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.10.100.100", 80));
//		HttpURLConnection connection =(HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy);
//		connection.setDoOutput(true);
//		connection.setDoInput(true);
//		connection.setRequestProperty("Content-type", "text/xml");
//		connection.setRequestProperty("Accept", "text/xml, application/xml");
//		connection.setRequestMethod("POST");
	}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:49,代碼來源:YadaHttpUtil.java

示例12: post

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private void post(String method, Object req) {
    ApiReq apiReq = ApiUtil.genApiReq(ApiConstant.APP_ID_DEMO, ApiConstant.APP_KEY_DEMO, method, req);
    String apiReqStr = JsonUtil.writeValueQuite(apiReq);
    String encodeApiReq = Base64Utils.encodeToString(apiReqStr.getBytes());

    HttpUtil.httpPostRequest(LOCAL_URL, new X5Req(encodeApiReq));
}
 
開發者ID:slking1987,項目名稱:mafia,代碼行數:8,代碼來源:ApiControllerTest.java

示例13: getWebsocketAcceptResponse

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
private String getWebsocketAcceptResponse() throws NoSuchAlgorithmException {
	Matcher matcher = WEBSOCKET_KEY_PATTERN.matcher(this.header);
	if (!matcher.find()) {
		throw new IllegalStateException("No Sec-WebSocket-Key");
	}
	String response = matcher.group(1).trim() + WEBSOCKET_GUID;
	MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
	messageDigest.update(response.getBytes(), 0, response.length());
	return Base64Utils.encodeToString(messageDigest.digest());
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:11,代碼來源:Connection.java

示例14: testLoginHandlerFail

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
@Test
public void testLoginHandlerFail() throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
	register.unregister("sample");
	List<LSPayload> payloads = new LinkedList<>();
	LoginHandler handler = new LoginHandler(userDB, register);
	byte[] macKey = TestUtils.generateMACKey();
	LSRequest req;
	DefaultLSSession.createSession("noexist");
	WebSocket socket = new MockWebSocket();
	req = new LSRequest("noexist", new HashMap<>(), new Date(), LSRequest.LS_LOGIN,
			Base64Utils.encodeToString(macKey), socket);
	req.getAttributes().put("signature", "random stuff");
	LSResponse resp = handler.handleRequest(req, payloads);
	Assert.assertEquals(LSResponse.LOGIN_FAIL, resp.getStatus());
	Assert.assertEquals(null, register.getSocket("noexist"));

	socket = new MockWebSocket();
	KeyPair wrongKeys = TestUtils.generateKeyPair();
	DefaultLSSession.createSession("sample");
	req = new LSRequest("sample", new HashMap<>(), new Date(), LSRequest.LS_LOGIN,
			Base64Utils.encodeToString(macKey), socket);
	req.getAttributes().put("signature",
			AuthenticationUtils.INSTANCE.signMessage(req.getData(), req.getTimeStamp(), wrongKeys.getPrivate()));
	resp = handler.handleRequest(req, payloads);
	Assert.assertEquals(LSResponse.LOGIN_FAIL, resp.getStatus());
	Assert.assertEquals(null, register.getSocket("sample"));
	Assert.assertEquals(false, req.getSession().containsAttribute("macKey"));
	Assert.assertEquals(0, payloads.size());
}
 
開發者ID:shilongdai,項目名稱:LSChatServer,代碼行數:30,代碼來源:LoginHandlerTest.java

示例15: intercept

import org.springframework.util.Base64Utils; //導入方法依賴的package包/類
@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);
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:9,代碼來源:BasicAuthorizationInterceptor.java


注:本文中的org.springframework.util.Base64Utils.encodeToString方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。