1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * @(#)BASE64EncoderStream.java       1.6 02/03/27
  28  */
  29 
  30 
  31 
  32 package com.sun.xml.internal.messaging.saaj.packaging.mime.util;
  33 
  34 import java.io.*;
  35 
  36 /**
  37  * This class implements a BASE64 Encoder. It is implemented as
  38  * a FilterOutputStream, so one can just wrap this class around
  39  * any output stream and write bytes into this filter. The Encoding
  40  * is done as the bytes are written out.
  41  *
  42  * @author John Mani
  43  * @author Bill Shannon
  44  */
  45 
  46 public class BASE64EncoderStream extends FilterOutputStream {
  47     private byte[] buffer;      // cache of bytes that are yet to be encoded
  48     private int bufsize = 0;    // size of the cache
  49     private int count = 0;      // number of bytes that have been output
  50     private int bytesPerLine;   // number of bytes per line
  51 
  52     /**
  53      * Create a BASE64 encoder that encodes the specified input stream
  54      * @param out        the output stream
  55      * @param bytesPerLine  number of bytes per line. The encoder inserts
  56      *                   a CRLF sequence after the specified number of bytes
  57      */
  58     public BASE64EncoderStream(OutputStream out, int bytesPerLine) {
  59         super(out);
  60         buffer = new byte[3];
  61         this.bytesPerLine = bytesPerLine;
  62     }
  63 
  64     /**
  65      * Create a BASE64 encoder that encodes the specified input stream.
  66      * Inserts the CRLF sequence after outputting 76 bytes.
  67      * @param out        the output stream
  68      */
  69     public BASE64EncoderStream(OutputStream out) {
  70         this(out, 76);
  71     }
  72 
  73     /**
  74      * Encodes <code>len</code> bytes from the specified
  75      * <code>byte</code> array starting at offset <code>off</code> to
  76      * this output stream.
  77      *
  78      * @param      b     the data.
  79      * @param      off   the start offset in the data.
  80      * @param      len   the number of bytes to write.
  81      * @exception  IOException  if an I/O error occurs.
  82      */
  83     @Override
  84     public void write(byte[] b, int off, int len) throws IOException {
  85         for (int i = 0; i < len; i++)
  86             write(b[off + i]);
  87     }
  88 
  89     /**
  90      * Encodes <code>b.length</code> bytes to this output stream.
  91      * @param      b   the data to be written.
  92      * @exception  IOException  if an I/O error occurs.
  93      */
  94     @Override
  95     public void write(byte[] b) throws IOException {
  96         write(b, 0, b.length);
  97     }
  98 
  99     /**
 100      * Encodes the specified <code>byte</code> to this output stream.
 101      * @param      c   the <code>byte</code>.
 102      * @exception  IOException  if an I/O error occurs.
 103      */
 104     @Override
 105     public void write(int c) throws IOException {
 106         buffer[bufsize++] = (byte)c;
 107         if (bufsize == 3) { // Encoding unit = 3 bytes
 108             encode();
 109             bufsize = 0;
 110         }
 111     }
 112 
 113     /**
 114      * Flushes this output stream and forces any buffered output bytes
 115      * to be encoded out to the stream.
 116      * @exception  IOException  if an I/O error occurs.
 117      */
 118     @Override
 119     public void flush() throws IOException {
 120         if (bufsize > 0) { // If there's unencoded characters in the buffer ..
 121             encode();      // .. encode them
 122             bufsize = 0;
 123         }
 124         out.flush();
 125     }
 126 
 127     /**
 128      * Forces any buffered output bytes to be encoded out to the stream
 129      * and closes this output stream
 130      */
 131     @Override
 132     public void close() throws IOException {
 133         flush();
 134         out.close();
 135     }
 136 
 137     /** This array maps the characters to their 6 bit values */
 138     private final static char pem_array[] = {
 139         'A','B','C','D','E','F','G','H', // 0
 140         'I','J','K','L','M','N','O','P', // 1
 141         'Q','R','S','T','U','V','W','X', // 2
 142         'Y','Z','a','b','c','d','e','f', // 3
 143         'g','h','i','j','k','l','m','n', // 4
 144         'o','p','q','r','s','t','u','v', // 5
 145         'w','x','y','z','0','1','2','3', // 6
 146         '4','5','6','7','8','9','+','/'  // 7
 147     };
 148 
 149     private void encode() throws IOException {
 150         // If writing out this encoded unit will cause overflow,
 151         // start a new line.
 152         if (count + 4 > bytesPerLine) {
 153             out.write('\r');
 154             out.write('\n');
 155             count = 0;
 156         }
 157 
 158         byte a, b, c;
 159         if (bufsize == 1) {
 160             a = buffer[0];
 161             b = 0;
 162             c = 0;
 163             out.write(pem_array[(a >>> 2) & 0x3F]);
 164             out.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
 165             out.write('='); // pad character
 166             out.write('='); // pad character
 167         } else if (bufsize == 2) {
 168             a = buffer[0];
 169             b = buffer[1];
 170             c = 0;
 171             out.write(pem_array[(a >>> 2) & 0x3F]);
 172             out.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
 173             out.write(pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
 174             out.write('='); // pad character
 175         } else {
 176             a = buffer[0];
 177             b = buffer[1];
 178             c = buffer[2];
 179             out.write(pem_array[(a >>> 2) & 0x3F]);
 180             out.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
 181             out.write(pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
 182             out.write(pem_array[c & 0x3F]);
 183         }
 184 
 185         // increment count
 186         count += 4;
 187     }
 188 
 189     /**
 190      * Base64 encode a byte array.  No line breaks are inserted.
 191      * This method is suitable for short strings, such as those
 192      * in the IMAP AUTHENTICATE protocol, but not to encode the
 193      * entire content of a MIME part.
 194      *
 195      * @param inbuf byte array to encode.
 196      *
 197      * @return encoded byte array.
 198      */
 199     public static byte[] encode(byte[] inbuf) {
 200         if (inbuf.length == 0)
 201             return inbuf;
 202         byte[] outbuf = new byte[((inbuf.length + 2) / 3) * 4];
 203         int inpos = 0, outpos = 0;
 204         int size = inbuf.length;
 205         while (size > 0) {
 206             byte a, b, c;
 207             if (size == 1) {
 208                 a = inbuf[inpos++];
 209                 b = 0;
 210                 c = 0;
 211                 outbuf[outpos++] = (byte)pem_array[(a >>> 2) & 0x3F];
 212                 outbuf[outpos++] =
 213                         (byte)pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
 214                 outbuf[outpos++] = (byte)'=';  // pad character
 215                 outbuf[outpos++] = (byte)'=';  // pad character
 216             } else if (size == 2) {
 217                 a = inbuf[inpos++];
 218                 b = inbuf[inpos++];
 219                 c = 0;
 220                 outbuf[outpos++] = (byte)pem_array[(a >>> 2) & 0x3F];
 221                 outbuf[outpos++] =
 222                         (byte)pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
 223                 outbuf[outpos++] =
 224                         (byte)pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];
 225                 outbuf[outpos++] = (byte)'=';  // pad character
 226             } else {
 227                 a = inbuf[inpos++];
 228                 b = inbuf[inpos++];
 229                 c = inbuf[inpos++];
 230                 outbuf[outpos++] = (byte)pem_array[(a >>> 2) & 0x3F];
 231                 outbuf[outpos++] =
 232                         (byte)pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
 233                 outbuf[outpos++] =
 234                         (byte)pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];
 235                 outbuf[outpos++] = (byte)pem_array[c & 0x3F];
 236             }
 237             size -= 3;
 238         }
 239         return outbuf;
 240     }
 241 
 242     /*** begin TEST program
 243     public static void main(String argv[]) throws Exception {
 244         FileInputStream infile = new FileInputStream(argv[0]);
 245         BASE64EncoderStream encoder = new BASE64EncoderStream(System.out);
 246         int c;
 247 
 248         while ((c = infile.read()) != -1)
 249             encoder.write(c);
 250         encoder.close();
 251     }
 252     *** end TEST program **/
 253 }