本文整理汇总了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"))));
}
示例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());
}
示例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);
}
}
示例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);
}
}
示例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-----";
}
示例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);
}
示例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 {
}
}
示例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 {
}
}
示例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);
}
}
示例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);
}
}
示例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");
}
示例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));
}
示例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());
}
示例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);
}