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