Java Code Examples for java.util.Base64#Encoder
The following examples show how to use
java.util.Base64#Encoder .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openjdk-jdk8u-backup File: Base64GetEncoderTest.java License: GNU General Public License v2.0 | 6 votes |
private static void testWrapEncode2(final Base64.Encoder encoder) throws IOException { System.err.println("\nEncoder.wrap test II "); final byte[] secondTestBuffer = "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]" .getBytes(US_ASCII); String base64EncodedString; ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream(); OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream); base64EncodingStream.write(secondTestBuffer); base64EncodingStream.close(); final byte[] encodedByteArray = secondEncodingStream.toByteArray(); System.err.print("result = " + new String(encodedByteArray, US_ASCII) + " after wrap Base64 encoding of string"); base64EncodedString = new String(encodedByteArray, US_ASCII); if (base64EncodedString.contains("$$$")) { throw new RuntimeException( "Base64 encoding contains line separator after wrap 2 invoked ... \n"); } }
Example 2
Source Project: gpmall File: Base64Util.java License: Apache License 2.0 | 6 votes |
/** * @param args */ public static void main(String[] args) { try { final Base64.Decoder decoder = Base64.getDecoder(); final Base64.Encoder encoder = Base64.getEncoder(); final String text = "字串文字"; final byte[] textByte = text.getBytes("UTF-8"); //编码 final String encodedText = encoder.encodeToString(textByte); System.out.println(encodedText); //解码 System.out.println(new String(decoder.decode(encodedText), "UTF-8")); } catch (Exception e) { e.printStackTrace(); } }
Example 3
Source Project: jdk8u-jdk File: Base64GetEncoderTest.java License: GNU General Public License v2.0 | 6 votes |
private static void testWrapEncode1(final Base64.Encoder encoder) throws IOException { System.err.println("\nEncoder.wrap test I "); final byte[] bytesIn = "fo".getBytes(US_ASCII); String base64EncodedString; ByteArrayOutputStream encodingStream = new ByteArrayOutputStream(); OutputStream encoding = encoder.wrap(encodingStream); encoding.write(bytesIn); encoding.close(); final byte[] encodedBytes = encodingStream.toByteArray(); System.err.print("result = " + new String(encodedBytes, US_ASCII) + " after the Base64 encoding \n"); base64EncodedString = new String(encodedBytes, US_ASCII); if (base64EncodedString.contains("$$$")) { throw new RuntimeException( "Base64 encoding contains line separator after wrap I test ... \n"); } }
Example 4
Source Project: openjdk-8 File: Base64GetEncoderTest.java License: GNU General Public License v2.0 | 6 votes |
private static void testEncodeToStringWithLongInputData( final Base64.Encoder encoder) { System.err.println("\n\nEncoder.encodeToStringWithLongInputData test "); final byte[] secondTestBuffer = "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]" .getBytes(US_ASCII); String base64EncodedString; base64EncodedString = encoder.encodeToString(secondTestBuffer); System.err.println("Second Base64 encoded string is " + base64EncodedString); if (base64EncodedString.contains("$$$")) { throw new RuntimeException( "Base64 encoding contains line separator after encodeToString invoked ... \n"); } }
Example 5
Source Project: flash-waimai File: CaptchaController.java License: MIT License | 6 votes |
@RequestMapping(value = "/v1/captchas", method = RequestMethod.POST) public Object get() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Map<String, Object> map = CaptchaCode.getImageCode(60, 20, outputStream); String captchCodeId = UUID.randomUUID().toString(); tokenCache.put(captchCodeId, map.get("strEnsure").toString().toLowerCase()); logger.info("captchCode:{}", map.get("strEnsure").toString().toLowerCase()); try { ImageIO.write((BufferedImage) map.get("image"), "png", outputStream); Base64.Encoder encoder = Base64.getEncoder(); String base64 = new String(encoder.encode(outputStream.toByteArray()));; String captchaBase64 = "data:image/png;base64," + base64.replaceAll("\r\n", ""); return Rets.success(Maps.newHashMap("captchCodeId",captchCodeId,"code",captchaBase64)); } catch (IOException e) { return Rets.failure(e.getMessage()); } }
Example 6
Source Project: jdk8u-jdk File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static void testIOE(final Base64.Encoder enc) throws Throwable { ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); final OutputStream os = enc.wrap(baos); os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9}); os.close(); checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }}); checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }}); checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }}); }
Example 7
Source Project: openjdk-8-source File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected) throws Throwable { ByteBuffer bout = enc.encode(bin); byte[] buf = new byte[bout.remaining()]; bout.get(buf); if (bin.hasRemaining()) { throw new RuntimeException( "Base64 enc.encode(ByteBuffer) failed!"); } checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!"); }
Example 8
Source Project: openjdk-jdk9 File: Http2ClientImpl.java License: GNU General Public License v2.0 | 5 votes |
/** Returns the client settings as a base64 (url) encoded string */ String getSettingsString() { SettingsFrame sf = getClientSettings(); byte[] settings = sf.toByteArray(); // without the header Base64.Encoder encoder = Base64.getUrlEncoder() .withoutPadding(); return encoder.encodeToString(settings); }
Example 9
Source Project: jdk8u_jdk File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected) throws Throwable { ByteBuffer bout = enc.encode(bin); byte[] buf = new byte[bout.remaining()]; bout.get(buf); if (bin.hasRemaining()) { throw new RuntimeException( "Base64 enc.encode(ByteBuffer) failed!"); } checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!"); }
Example 10
Source Project: java-docs-samples File: DeviceRegistryExample.java License: Apache License 2.0 | 5 votes |
/** Send a command to a device. * */ // [START iot_send_command] protected static void sendCommand( String deviceId, String projectId, String cloudRegion, String registryName, String data) throws GeneralSecurityException, IOException { GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all()); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); HttpRequestInitializer init = new HttpCredentialsAdapter(credential); final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init) .setApplicationName(APP_NAME) .build(); final String devicePath = String.format( "projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryName, deviceId); SendCommandToDeviceRequest req = new SendCommandToDeviceRequest(); // Data sent through the wire has to be base64 encoded. Base64.Encoder encoder = Base64.getEncoder(); String encPayload = encoder.encodeToString(data.getBytes(StandardCharsets.UTF_8.name())); req.setBinaryData(encPayload); System.out.printf("Sending command to %s%n", devicePath); service .projects() .locations() .registries() .devices() .sendCommandToDevice(devicePath, req) .execute(); System.out.println("Command response: sent"); }
Example 11
Source Project: geoportal-server-harvester File: TextScrambler.java License: Apache License 2.0 | 5 votes |
private static String hash(String string) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(string.getBytes("UTF-8")); byte[] digest = md.digest(); Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(digest); }
Example 12
Source Project: dragonwell8_jdk File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static void testEncoderKeepsSilence(Base64.Encoder enc) throws Throwable { List<Integer> vals = Arrays.asList(Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111, Integer.MAX_VALUE - 1, Integer.MAX_VALUE, rnd.nextInt(), rnd.nextInt(), rnd.nextInt(), rnd.nextInt()); byte[] buf = new byte[] {1, 0, 91}; for (int off : vals) { for (int len : vals) { if (off >= 0 && len >= 0 && off <= buf.length - len) { // valid args, skip them continue; } // invalid args, test them System.out.println("testing off=" + off + ", len=" + len); ByteArrayOutputStream baos = new ByteArrayOutputStream(100); try (OutputStream os = enc.wrap(baos)) { os.write(buf, off, len); throw new RuntimeException("Expected IOOBEx was not thrown"); } catch (IndexOutOfBoundsException expected) { } if (baos.size() > 0) throw new RuntimeException("No output was expected, but got " + baos.size() + " bytes"); } } }
Example 13
Source Project: hottub File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static void testDecodeIgnoredAfterPadding() throws Throwable { for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) { byte[][] src = new byte[][] { "A".getBytes("ascii"), "AB".getBytes("ascii"), "ABC".getBytes("ascii"), "ABCD".getBytes("ascii"), "ABCDE".getBytes("ascii") }; Base64.Encoder encM = Base64.getMimeEncoder(); Base64.Decoder decM = Base64.getMimeDecoder(); Base64.Encoder enc = Base64.getEncoder(); Base64.Decoder dec = Base64.getDecoder(); for (int i = 0; i < src.length; i++) { // decode(byte[]) byte[] encoded = encM.encode(src[i]); encoded = Arrays.copyOf(encoded, encoded.length + 1); encoded[encoded.length - 1] = nonBase64; checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored"); byte[] decoded = new byte[src[i].length]; decM.decode(encoded, decoded); checkEqual(decoded, src[i], "Non-base64 char is not ignored"); try { dec.decode(encoded); throw new RuntimeException("No IAE for non-base64 char"); } catch (IllegalArgumentException iae) {} } } }
Example 14
Source Project: TencentKona-8 File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static void testEncoderKeepsSilence(Base64.Encoder enc) throws Throwable { List<Integer> vals = Arrays.asList(Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111, Integer.MAX_VALUE - 1, Integer.MAX_VALUE, rnd.nextInt(), rnd.nextInt(), rnd.nextInt(), rnd.nextInt()); byte[] buf = new byte[] {1, 0, 91}; for (int off : vals) { for (int len : vals) { if (off >= 0 && len >= 0 && off <= buf.length - len) { // valid args, skip them continue; } // invalid args, test them System.out.println("testing off=" + off + ", len=" + len); ByteArrayOutputStream baos = new ByteArrayOutputStream(100); try (OutputStream os = enc.wrap(baos)) { os.write(buf, off, len); throw new RuntimeException("Expected IOOBEx was not thrown"); } catch (IndexOutOfBoundsException expected) { } if (baos.size() > 0) throw new RuntimeException("No output was expected, but got " + baos.size() + " bytes"); } } }
Example 15
Source Project: dolphin-platform File: Base64Utils.java License: Apache License 2.0 | 5 votes |
public static String toBase64(final Serializable data) throws IOException { final ByteArrayOutputStream rawOutputStream = new ByteArrayOutputStream(); final ObjectOutputStream dataOutputStream = new ObjectOutputStream(rawOutputStream); dataOutputStream.writeObject(data); Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(rawOutputStream.toByteArray()); }
Example 16
Source Project: jdk8u60 File: TestBase64.java License: GNU General Public License v2.0 | 5 votes |
private static void testIOE(final Base64.Encoder enc) throws Throwable { ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); final OutputStream os = enc.wrap(baos); os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9}); os.close(); checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }}); checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }}); checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }}); }
Example 17
Source Project: sakai File: LTI13Util.java License: Educational Community License v2.0 | 4 votes |
public static Map<String, String> generateKeys() throws java.security.NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair kp = keyGen.genKeyPair(); byte[] publicKey = kp.getPublic().getEncoded(); byte[] privateKey = kp.getPrivate().getEncoded(); Base64.Encoder encoder = Base64.getEncoder(); String publicRSA = "-----BEGIN PUBLIC KEY-----\n" + encoder.encodeToString(privateKey) + "\n-----END PUBLIC KEY-----\n"; String privateRSA = "-----BEGIN PRIVATE KEY-----\n" + encoder.encodeToString(privateKey) + "\n-----END PRIVATE KEY-----\n"; // If we need a pem style for these keys // String pemBase64 = javax.xml.bind.DatatypeConverter.printBase64Binary(publicKey); Map<String, String> returnMap = new TreeMap<>(); returnMap.put("platform_public", publicRSA); returnMap.put("platform_private", privateRSA); // Do it again for the tool keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); kp = keyGen.genKeyPair(); publicKey = kp.getPublic().getEncoded(); privateKey = kp.getPrivate().getEncoded(); publicRSA = "-----BEGIN RSA PUBLIC KEY-----\n" + encoder.encodeToString(privateKey) + "\n-----END RSA PUBLIC KEY-----\n"; privateRSA = "-----BEGIN RSA PRIVATE KEY-----\n" + encoder.encodeToString(privateKey) + "\n-----END RSA PRIVATE KEY-----\n"; returnMap.put("tool_public", publicRSA); returnMap.put("tool_private", privateRSA); return returnMap; }
Example 18
Source Project: LoggerPlusPlus File: Base64Exporter.java License: GNU Affero General Public License v3.0 | 4 votes |
public void exportEntries(List<LogEntry> entries, boolean includeRequest, boolean includeResponse) { if (!includeRequest && !includeResponse) throw new IllegalArgumentException("Must include either request, response or both."); try { File file = MoreHelp.getSaveFile("LoggerPlusPlus_Base64.json", "JSON Format", "json"); if (file.exists() && !MoreHelp.shouldOverwriteExistingFilePrompt()) return; SwingWorkerWithProgressDialog<Void> importWorker = new SwingWorkerWithProgressDialog<Void>( LoggerPlusPlus.instance.getLoggerFrame(), "Base64 Encoded JSON Export", "Exporting as Base64 encoded JSON...", entries.size()) { @Override protected Void doInBackground() throws Exception { super.doInBackground(); try (FileWriter fileWriter = new FileWriter(file, false)) { Gson gson = exportController.getLoggerPlusPlus().getGsonProvider().getGson(); ArrayList<JsonObject> jsonEntries = new ArrayList<>(); Base64.Encoder encoder = Base64.getEncoder(); for (LogEntry entry : entries) { JsonObject jsonEntry = new JsonObject(); if (includeRequest) { jsonEntry.addProperty("request", encoder.encodeToString(entry.requestResponse.getRequest())); } if (includeResponse) { jsonEntry.addProperty("response", encoder.encodeToString(entry.requestResponse.getResponse())); } jsonEntries.add(jsonEntry); } gson.toJson(jsonEntries, fileWriter); } return null; } @Override protected void done() { super.done(); JOptionPane.showMessageDialog(LoggerPlusPlus.instance.getLoggerFrame(), "Export as Base64 completed.", "Base64 Export", JOptionPane.INFORMATION_MESSAGE); } }; importWorker.execute(); } catch (Exception e) { //Cancelled. } }
Example 19
Source Project: openjdk-jdk8u-backup File: Base64GetEncoderTest.java License: GNU General Public License v2.0 | 3 votes |
private static void testEncodeToString(final Base64.Encoder encoder) { final byte[] bytesIn = "fo".getBytes(US_ASCII); System.err.println("\nEncoder.encodeToString test "); String base64EncodedString = encoder.encodeToString(bytesIn); System.err.println("Base64 encoded string is " + base64EncodedString); if (base64EncodedString.contains("$$$")) { throw new RuntimeException("Base64 encoding contains line separator after Encoder.encodeToString invoked ... \n"); } }
Example 20
Source Project: openjdk-jdk8u File: Base64GetEncoderTest.java License: GNU General Public License v2.0 | 3 votes |
public static void main(String args[]) throws Throwable { final Base64.Encoder encoder = Base64.getMimeEncoder(0, "$$$".getBytes(US_ASCII)); testEncodeToString(encoder); testWrapEncode1(encoder); testEncodeToStringWithLongInputData(encoder); testWrapEncode2(encoder); }