001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import java.nio.ByteBuffer; 005 006public final class Base64 { 007 008 private Base64() { 009 // Hide default constructor for utils classes 010 } 011 012 private static String encDefault = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 013 private static String encUrlSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; 014 015 public static String encode(String s) { 016 return encode(s, false); 017 } 018 019 public static String encode(String s, boolean urlsafe) { 020 StringBuilder out = new StringBuilder(); 021 String enc = urlsafe ? encUrlSafe : encDefault; 022 for (int i = 0; i < (s.length()+2)/3; ++i) { 023 int l = Math.min(3, s.length()-i*3); 024 String buf = s.substring(i*3, i*3+l); 025 out.append(enc.charAt(buf.charAt(0)>>2)); 026 out.append(enc.charAt( 027 (buf.charAt(0) & 0x03) << 4 | 028 (l==1? 029 0: 030 (buf.charAt(1) & 0xf0) >> 4))); 031 out.append(l>1?enc.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2?0:(buf.charAt(2) & 0xc0) >> 6)):'='); 032 out.append(l>2?enc.charAt(buf.charAt(2) & 0x3f):'='); 033 } 034 return out.toString(); 035 } 036 037 public static String encode(ByteBuffer s) { 038 return encode(s, false); 039 } 040 041 public static String encode(ByteBuffer s, boolean urlsafe) { 042 StringBuilder out = new StringBuilder(); 043 String enc = urlsafe ? encUrlSafe : encDefault; 044 // Read 3 bytes at a time. 045 for (int i = 0; i < (s.limit()+2)/3; ++i) { 046 int l = Math.min(3, s.limit()-i*3); 047 int byte0 = s.get() & 0xff; 048 int byte1 = l>1? s.get() & 0xff : 0; 049 int byte2 = l>2? s.get() & 0xff : 0; 050 051 out.append(enc.charAt(byte0>>2)); 052 out.append(enc.charAt( 053 (byte0 & 0x03) << 4 | 054 (l==1? 055 0: 056 (byte1 & 0xf0) >> 4))); 057 out.append(l>1?enc.charAt((byte1 & 0x0f) << 2 | (l==2?0:(byte2 & 0xc0) >> 6)):'='); 058 out.append(l>2?enc.charAt(byte2 & 0x3f):'='); 059 } 060 return out.toString(); 061 } 062}