本文整理匯總了Java中java.util.Base64類的典型用法代碼示例。如果您正苦於以下問題:Java Base64類的具體用法?Java Base64怎麽用?Java Base64使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Base64類屬於java.util包,在下文中一共展示了Base64類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: zipBase64
import java.util.Base64; //導入依賴的package包/類
/**
* Combines multiple files into a ZIP archive, then base-64 the ZIP archive.
*
* @param paths a list of one or more input files, that are to be compressed together
* @return the compressed output, as a String
*/
private static String zipBase64(List<Path> paths) {
if (paths.isEmpty()) {
throw new IllegalArgumentException("PortfolioDataFile requires at least one file");
}
try {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 8)) {
try (OutputStream baseos = Base64.getEncoder().wrap(baos)) {
try (ZipOutputStream zos = new ZipOutputStream(baseos)) {
for (Path path : paths) {
ZipEntry entry = new ZipEntry(path.getFileName().toString());
zos.putNextEntry(entry);
Files.copy(path, zos);
zos.closeEntry();
}
}
}
return baos.toString("ISO-8859-1"); // base-64 bytes are ASCII, so this is optimal
}
} catch (IOException ex) {
throw new UncheckedIOException("Failed to zip base-64 content", ex);
}
}
示例2: Image
import java.util.Base64; //導入依賴的package包/類
public Image(long code) throws IOException {
try {
this.bufferedImage = ImageIO.read(new File(DEFAULT_LOCATION));
sideLength = bufferedImage.getWidth() / 16;
} catch (IOException e) {
Logger.getGlobal().log(Level.SEVERE, String.valueOf(e));
}
for (int i = 0; i < 33; i++) {
if ((code & ((long) 1 << (32 - i))) != 0L) {
drawTopLeft(i);
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
byte[] bufferedImageBytes = baos.toByteArray();
this.base64 = Base64.getEncoder().encodeToString(bufferedImageBytes);
}
示例3: main
import java.util.Base64; //導入依賴的package包/類
public static void main(String[] args) {
Base64.Decoder b64decoder = Base64.getUrlDecoder();
final Undertow server = Undertow.builder()
.addHttpListener(8083, "localhost")
.setHandler(exchange -> {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
String credential = exchange.getRequestHeaders().getFirst("X-Bouncr-Credential");
String[] tokens = credential.split("\\.", 3);
String json = new String(b64decoder.decode(tokens[1]));
exchange.getResponseSender().send("Server1\n"
+ "profile=" + json + "\n"
);
})
.build();
Runtime.getRuntime().addShutdownHook(new Thread(server::stop));
server.start();
}
示例4: getDERPublicKeyFromPEM
import java.util.Base64; //導入依賴的package包/類
private PublicKey getDERPublicKeyFromPEM(String key) throws Exception {
try {
// strip of header, footer, newlines, whitespaces
String publicKeyPEM = key
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation
byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
return publicKey;
} catch (Exception e) {
throw new InvalidConfig("Invalid JWE public key");
}
}
示例5: authenticate
import java.util.Base64; //導入依賴的package包/類
private boolean authenticate(String authInfo) throws IOException {
boolean matched = false;
try {
authInfo.trim();
int ind = authInfo.indexOf(' ');
String recvdUserPlusPass = authInfo.substring(ind + 1).trim();
// extract encoded (username:passwd
if (userPlusPass.equals(
new String( Base64.getMimeDecoder()
.decode(recvdUserPlusPass))))
{
matched = true;
}
} catch (Exception e) {
throw new IOException(
"Proxy received invalid Proxy-Authorization value: "
+ authInfo);
}
return matched;
}
示例6: addOrUpdateAccount
import java.util.Base64; //導入依賴的package包/類
private static void addOrUpdateAccount(String account, String password, String level)
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("REPLACE accounts(login, password, accessLevel) VALUES (?, ?, ?)"))
{
final MessageDigest md = MessageDigest.getInstance("SHA");
final byte[] newPassword = md.digest(password.getBytes("UTF-8"));
ps.setString(1, account);
ps.setString(2, Base64.getEncoder().encodeToString(newPassword));
ps.setString(3, level);
if (ps.executeUpdate() > 0)
{
System.out.println("Account " + account + " has been created or updated");
}
else
{
System.out.println("Account " + account + " does not exist");
}
}
catch (Exception e)
{
System.out.println("There was error while adding/updating account:");
System.out.println(e.getMessage());
}
}
示例7: encrypt
import java.util.Base64; //導入依賴的package包/類
/**
* 數據加密,算法(DES)
*
* @param data
* 要進行加密的數據
* @param desKey DES密鑰
* @return 加密後的數據
*/
public static String encrypt(String data, byte[] desKey) {
String encryptedData = null;
try {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(desKey);
// 創建一個密匙工廠,然後用它把DESKeySpec轉換成一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(deskey);
// 加密對象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
// 加密,並把字節數組編碼成字符串
encryptedData = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
} catch (Exception e) {
// log.error("加密錯誤,錯誤信息:", e);
throw new RuntimeException("加密錯誤,錯誤信息:", e);
}
return encryptedData;
}
示例8: readQuotedBytes
import java.util.Base64; //導入依賴的package包/類
private Token readQuotedBytes() throws IOException {
int c;
for (;;) {
c = in.read();
switch (c) {
case -1:
throw new EOFException("Unexpected EOF reading quoted bytes at line " + getLine() + ":" + getCol());
case '\n':
throw new EOFException("Unexpected end of line reading quoted bytes at line " + getLine() + ":" + getCol());
case '`':
// End the bytes
return new Token(Base64.getDecoder().decode(getToken(false, false).getBytes(UTF_8)), TokenType.BYTES);
default:
// Only allow valid Base64 characters: A-Z,a-z,0-9,\+
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') {
// Simply append to string so far
token.append((char) c);
} else {
throw new IOException("Expected base64 character but got " + (char) c + " at line " + getLine() + ":" + getCol());
}
}
}
}
示例9: callEchoBASIC
import java.util.Base64; //導入依賴的package包/類
@RunAsClient
@Test(groups = TCKConstants.TEST_GROUP_JAXRS,
description = "Attempting access with BASIC auth header should fail with HTTP_UNAUTHORIZED")
public void callEchoBASIC() throws Exception {
Reporter.log("callEchoBASIC, expect HTTP_UNAUTHORIZED");
byte[] tokenb = Base64.getEncoder().encode("[email protected]:password".getBytes());
String token = new String(tokenb);
System.out.printf("basic: %s\n", token);
String uri = baseURL.toExternalForm() + "/endp/echo";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam("input", "hello")
;
Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "BASIC "+token).get();
Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_UNAUTHORIZED);
String reply = response.readEntity(String.class);
System.out.println(reply);
}
示例10: getPasswordHash
import java.util.Base64; //導入依賴的package包/類
public static String getPasswordHash(String p_password, byte[] p_seed) {
byte[] pwd = p_password.getBytes();
byte[] result = new byte[pwd.length+p_seed.length];
for (int i = 0; i<result.length;i++) {
if (i%2 == 0 && i/2<pwd.length) {
result[i] = pwd[i/2];
}
if ((i+1)%2 == 0 && (i+1)/2<p_seed.length) {
result[i] = p_seed[(i+1)/2];
}
}
MessageDigest md = null;
try { md = MessageDigest.getInstance("SHA-256");}
catch (NoSuchAlgorithmException e) {
_logger.error(e.getMessage(), e);
}
return Base64.getEncoder().encodeToString(md.digest(result));
}
示例11: getPEMPublicKeyFromDER
import java.util.Base64; //導入依賴的package包/類
private static String getPEMPublicKeyFromDER(PublicKey publicKey) {
String begin = "-----BEGIN PUBLIC KEY-----";
String end = "-----END PUBLIC KEY-----";
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
String key = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded());
return begin + "\n" + key + "\n" + end;
}
示例12: setPrivateKey
import java.util.Base64; //導入依賴的package包/類
/**
* Internal method used during parsing : sets the private key in this entry
*
* @param key the chunk containing certificate
* @throws CertificateException if key already exists
*/
private void setPrivateKey(List<String> key) throws CertificateException, NoSuchAlgorithmException {
if (privateKey != null) throw new CertificateException("More than one private key in PEM input");
String b64key = key.subList(1, key.size()-1).stream().collect(Collectors.joining());
byte[] binKey = Base64.getDecoder().decode(b64key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(binKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
try {
privateKey = kf.generatePrivate(keySpec);
}
catch (InvalidKeySpecException e) {
throw new CertificateException(e);
}
}
示例13: getUsernamePassword
import java.util.Base64; //導入依賴的package包/類
/**
* Returns the username and password from a Basic Authentication header.
*
* @param auth The Basic Authentication header.
* @return Either INVALID or a 2-item array.
*/
private static String[] getUsernamePassword(final String auth) {
if (auth == null || !auth.startsWith(BASIC_PREFIX)) {
// No Authorization header present
// or not Basic authentication
return INVALID;
}
final byte[] decodedBytes;
try {
decodedBytes = Base64.getDecoder().decode(auth.substring(BASIC_PREFIX.length()));
} catch (final IllegalArgumentException ex) {
return INVALID;
}
final String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
final int colonIndex = decoded.indexOf(':');
if (colonIndex == -1) {
// No colon means this is a malformed header.
return INVALID;
}
return decoded.split(":", 2);
}
示例14: maakSelectieTaak
import java.util.Base64; //導入依賴的package包/類
private SelectieVerwerkTaakBericht maakSelectieTaak(List<PersoonCache> caches, List<SelectieAutorisatieBericht> autorisatieChunk) {
SelectieVerwerkTaakBericht selectieTaak = new SelectieVerwerkTaakBericht();
final List<SelectiePersoonBericht> selectiePersonen = new ArrayList<>();
for (PersoonCache persoonCache : caches) {
final SelectiePersoonBericht selectiePersoonBericht = new SelectiePersoonBericht();
if (persoonCache.getAfnemerindicatieGegevens().length > 0) {
final String afnemerindicatieData =
new String(Base64.getEncoder().encode(persoonCache.getAfnemerindicatieGegevens()), StandardCharsets.UTF_8);
selectiePersoonBericht.setAfnemerindicatieGegevens(afnemerindicatieData);
}
if (persoonCache.getPersoonHistorieVolledigGegevens().length > 0) {
final String persoonData = new String(Base64.getEncoder().encode(persoonCache.getPersoonHistorieVolledigGegevens()), StandardCharsets.UTF_8);
selectiePersoonBericht.setPersoonHistorieVolledigGegevens(persoonData);
}
selectiePersonen.add(selectiePersoonBericht);
}
selectieTaak.setPersonen(selectiePersonen);
selectieTaak.setSelectieAutorisaties(autorisatieChunk);
selectieTaak.setSelectieRunId(selectie.getSelectierun().getId());
selectieTaak.setSelectieStartDatum(DatumUtil.vanDatumNaarInteger(selectie.getSelectierun().getTijdstipStart()));
return selectieTaak;
}
示例15: testGenerateFulfillment
import java.util.Base64; //導入依賴的package包/類
@Test
public final void testGenerateFulfillment() {
PskContext context = PskContext.fromReceiverAddress(TEST_SECRET, TEST_ADDRESS);
InterledgerPayment payment = InterledgerPayment.builder()
.destinationAccount(TEST_ADDRESS)
.destinationAmount(BigInteger.valueOf(100L))
.data(TEST_MESSAGE)
.build();
Fulfillment fulfillment = context.generateFulfillment(payment);
assertEquals("Incorrect fulfillment.",
((PreimageSha256Fulfillment) fulfillment).getPreimage(),
//TODO Fix crypto-conditions to use Bas64Url without padding
//Base64.getUrlEncoder().withoutPadding().encodeToString(TEST_PREIMAGE));
Base64.getUrlEncoder().encodeToString(TEST_PREIMAGE));
}