本文整理匯總了Java中java.util.Base64.Encoder類的典型用法代碼示例。如果您正苦於以下問題:Java Encoder類的具體用法?Java Encoder怎麽用?Java Encoder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Encoder類屬於java.util.Base64包,在下文中一共展示了Encoder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: test1
import java.util.Base64.Encoder; //導入依賴的package包/類
private static void test1() throws Exception {
byte[] src = new byte[] {
46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
-80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
byte[] encoded = encoder.encode(src);
Decoder decoder = Base64.getMimeDecoder();
byte[] decoded = decoder.decode(encoded);
if (!Objects.deepEquals(src, decoded)) {
throw new RuntimeException();
}
}
示例2: toJson
import java.util.Base64.Encoder; //導入依賴的package包/類
public static StringEntity toJson(Map<String, String> entries) {
Encoder encoder = Base64.getEncoder();
try {
return new StringEntity("[" + entries.entrySet().stream()
.map(entry -> {
String value = Optional.ofNullable(entry.getValue())
.map(entryValue -> "\"" + encoder.encodeToString(entryValue.getBytes()) + "\"")
.orElse("null");
return "{\"Key\":\"" + entry.getKey() + "\",\"Value\":" + value + "}";
})
.collect(Collectors.joining(",")) + "]");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
示例3: refreshToken
import java.util.Base64.Encoder; //導入依賴的package包/類
public void refreshToken(){
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
// Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in
builder.queryParam("grant_type", "refresh_token");
builder.queryParam("refresh_token", refreshToken);
// Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
HttpHeaders headers = new HttpHeaders();
Encoder encoder = Base64.getEncoder();
headers.add("Authorization","Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));
HttpEntity<String> entity = new HttpEntity<>("", headers);
ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class);
assertEquals(HttpStatus.OK, result2.getStatusCode());
// Obtain and keep the token
accessToken = result2.getBody().getValue();
assertNotNull(accessToken);
refreshToken = result2.getBody().getRefreshToken().getValue();
assertNotNull(refreshToken);
}
示例4: aesEncryptString
import java.util.Base64.Encoder; //導入依賴的package包/類
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] contentBytes = content.getBytes(charset);
byte[] keyBytes = key.getBytes(charset);
byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(encryptedBytes);
}
示例5: rfc4648Base64Encode
import java.util.Base64.Encoder; //導入依賴的package包/類
static String rfc4648Base64Encode(String arg) throws UnsupportedEncodingException {
Encoder encoder = Base64.getMimeEncoder(0, new byte[0]);
String res = encoder.encodeToString(arg.getBytes(TEXT_ENCODING));
res = res.replace("/", "_");
res = res.replace("+", "-");
res = res.replace("=", "");
return res;
}
示例6: createContent
import java.util.Base64.Encoder; //導入依賴的package包/類
public static Content createContent(IExtensionHelpers helpers, byte[] httpResponse) {
String[] response = new String(httpResponse).split("\r\n\r\n");
// size
int size = 0;
if (response.length > 1) {
size = response[1].getBytes().length;
}
// mimeType
String mimeType = getMimeType(httpResponse);
String base64String = "";
if (response.length > 1) {
IResponseInfo iResInfo = helpers.analyzeResponse(httpResponse);
int bodyPos = iResInfo.getBodyOffset();
byte[] bodybyte = Arrays.copyOfRange(httpResponse,bodyPos,httpResponse.length);
Encoder encoder = Base64.getMimeEncoder();
encoder = Base64.getMimeEncoder();
base64String = encoder.encodeToString(bodybyte);
}
Content retContent = new Content.Builder().size(size).compression(0).encoding("base64").mimeType(mimeType)
.text(base64String).build();
return retContent;
}
示例7: aesEncryptString
import java.util.Base64.Encoder; //導入依賴的package包/類
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] contentBytes = content.getBytes(charset);
byte[] keyBytes = key.getBytes(charset);
byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(encryptedBytes);
}
示例8: dumpCert
import java.util.Base64.Encoder; //導入依賴的package包/類
private void dumpCert(boolean rfc, Certificate certificate, PrintStream printstream) throws IOException, CertificateException {
if (rfc) {
final Encoder base64encoder = Base64.getEncoder();
final byte[] encoded = base64encoder.encode(certificate.getEncoded());
printstream.println("-----BEGIN CERTIFICATE-----");
printstream.write(encoded, 0, encoded.length);
printstream.println("-----END CERTIFICATE-----");
} else {
printstream.write(certificate.getEncoded());
}
}
示例9: generateApiKey
import java.util.Base64.Encoder; //導入依賴的package包/類
public static String generateApiKey(){
Encoder e = Base64.getEncoder();
ByteBuffer bb = ByteBuffer.wrap(new byte[16*2]);
for(int i=0;i<2; i++){
UUID u = UUID.randomUUID();
bb.putLong(u.getMostSignificantBits());
bb.putLong(u.getLeastSignificantBits());
}
return e.encodeToString(bb.array());
}
示例10: encryptIntegers
import java.util.Base64.Encoder; //導入依賴的package包/類
/**
* Encrypt an array of integers to a String.
*
* @param integers
* @param context
* @return
* @throws ServletException
*/
public static String encryptIntegers(int integers[], String password) throws ServletException {
/* Generate salt. */
SecureRandom rand = new SecureRandom();
byte salt[] = new byte[8];
rand.nextBytes(salt);
byte[] iv;
byte[] ciphertext;
try {
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Encrypt the SampleSetID. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ByteBuffer buff = ByteBuffer.allocate(integers.length * 4);
for (int i = 0; i < integers.length; ++i) {
buff.putInt(integers[i]);
}
ciphertext = cipher.doFinal(buff.array());
} catch (Exception ex) {
throw new ServletException(ex);
}
/* Store the encrypted SampleSetID in a cookie */
Encoder encoder = Base64.getEncoder();
String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
return encryptedStr;
}
示例11: encryptInteger
import java.util.Base64.Encoder; //導入依賴的package包/類
/**
* Encrypt an integer to a String.
*
* @param integer
* @param context
* @return
* @throws ServletException
*/
private static String encryptInteger(Integer integer, ServletContext context) throws ServletException {
/* Get password. */
String password = context.getInitParameter("SampleSetIDEncryptionPassword");
/* Generate salt. */
SecureRandom rand = new SecureRandom();
byte salt[] = new byte[8];
rand.nextBytes(salt);
byte[] iv;
byte[] ciphertext;
try {
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Encrypt the SampleSetID. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ciphertext = cipher.doFinal(ByteBuffer.allocate(4).putInt(integer).array());
} catch (Exception ex) {
throw new ServletException(ex);
}
/* Store the encrypted SampleSetID in a cookie */
Encoder encoder = Base64.getEncoder();
String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
return encryptedStr;
}
示例12: obtainTokenFromOuth2LoginEndpoint
import java.util.Base64.Encoder; //導入依賴的package包/類
@Test
public void obtainTokenFromOuth2LoginEndpoint() throws Exception {
obtainAuthorizationCode();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
// Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in
builder.queryParam("client_id", getClientId());
builder.queryParam("grant_type", "authorization_code");
builder.queryParam("code", authorizationCode);
builder.queryParam("redirect_uri", "http://anywhere");
// Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
HttpHeaders headers = new HttpHeaders();
Encoder encoder = Base64.getEncoder();
headers.add("Authorization","Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));
HttpEntity<String> entity = new HttpEntity<>("", headers);
ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class);
// This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token.
// Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the
// redirect_uri with the token after #
assertEquals(HttpStatus.OK, result2.getStatusCode());
// Obtain and keep the token
accessToken = result2.getBody().getValue();
assertNotNull(accessToken);
refreshToken = result2.getBody().getRefreshToken().getValue();
assertNotNull(refreshToken);
}
示例13: encode
import java.util.Base64.Encoder; //導入依賴的package包/類
/**
* Returns an encoded BASE64 string of the value.
*
* @param salt
* the salt to use for encoding
* @param value
* value to encode
*
* @return encoded BASE64 string of the value or null if no value given
*
* @throws CipherException
*/
public static String encode(String salt, String value)
throws CipherException
{
// verify value
if (null == value || value.isEmpty())
{
return null;
}
// create cipher object
SecretKeySpec keySpec = createAESCipher(salt);
Cipher cipher;
try
{
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] enc = cipher.doFinal(value.getBytes());
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(enc);
}
catch (Exception e)
{
throw new CipherException("Error during encryption.", e);
}
}
示例14: getEncoder
import java.util.Base64.Encoder; //導入依賴的package包/類
protected Encoder getEncoder() {
return encoder;
}
示例15: encodePropertyValue
import java.util.Base64.Encoder; //導入依賴的package包/類
private String encodePropertyValue(final String value) throws IllegalArgumentException, EncryptionException {
// simply obfuscate the values from clear text.
final Encoder encoder = Base64.getUrlEncoder();
final String encoded = encoder.encodeToString(value.getBytes());
return encoded;
}