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


Java Base64類代碼示例

本文整理匯總了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);
  }
}
 
開發者ID:OpenGamma,項目名稱:JavaSDK,代碼行數:29,代碼來源:PortfolioDataFile.java

示例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);
}
 
開發者ID:catalincraciun,項目名稱:scancode,代碼行數:21,代碼來源:Image.java

示例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();
}
 
開發者ID:kawasima,項目名稱:bouncr,代碼行數:20,代碼來源:ForTestBackendApp.java

示例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");
	}
}
 
開發者ID:gahana,項目名稱:edge-jwt-sample,代碼行數:19,代碼來源:JWTGenerator.java

示例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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:ProxyTunnelServer.java

示例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());
	}
}
 
開發者ID:rubenswagner,項目名稱:L2J-Global,代碼行數:26,代碼來源:SQLAccountManager.java

示例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;
    }
 
開發者ID:HujiangTechnology,項目名稱:Juice,代碼行數:29,代碼來源:DESUtil.java

示例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());
				}
		}
	}
}
 
開發者ID:Puppygames,項目名稱:thjson,代碼行數:24,代碼來源:THJSONTokenizer.java

示例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);
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:20,代碼來源:RolesAllowedTest.java

示例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));
}
 
開發者ID:awslabs,項目名稱:aws-photosharing-example,代碼行數:22,代碼來源:Security.java

示例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;
}
 
開發者ID:gahana,項目名稱:edge-jwt-sample,代碼行數:8,代碼來源:JWTValidatorTest.java

示例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);
    }
}
 
開發者ID:robymus,項目名稱:wowza-letsencrypt-converter,代碼行數:22,代碼來源:PemCertKey.java

示例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);
}
 
開發者ID:minijax,項目名稱:minijax,代碼行數:30,代碼來源:AuthUtils.java

示例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;
}
 
開發者ID:MinBZK,項目名稱:OperatieBRP,代碼行數:23,代碼來源:PersoonCacheConsumer.java

示例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));

}
 
開發者ID:hyperledger,項目名稱:quilt,代碼行數:21,代碼來源:PskContextTest.java


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