public static String encode(byte[] binaryValue) {

        int binaryValueLen = binaryValue.length;
        // Estimated output length (about 1.4x input, due to CRLF)
        int maxChars = (binaryValueLen * 7) / 5;
        // Buffer for encoded output
        StringBuffer sb = new StringBuffer(maxChars);

        int groupsToEOL = MAX_GROUPS_PER_LINE;
        // Convert groups of 3 input bytes, with pad if < 3 in final
        for (int binaryValueNdx = 0; binaryValueNdx < binaryValueLen;
             binaryValueNdx += 3) {

            // Encode 1st 6-bit group
            int group1 = (binaryValue[binaryValueNdx] >> 2) & 0x3F;
            sb.append(BASE64EncodingString.charAt(group1));

            // Encode 2nd 6-bit group
            int group2 = (binaryValue[binaryValueNdx] << 4) & 0x030;
            if ((binaryValueNdx+1) < binaryValueLen) {
                group2 = group2 
                       | ((binaryValue[binaryValueNdx+1] >> 4) & 0xF);
            }
            sb.append(BASE64EncodingString.charAt(group2));

            // Encode 3rd 6-bit group
            int group3;
            if ((binaryValueNdx+1) < binaryValueLen) {
                group3 = (binaryValue[binaryValueNdx+1] << 2) & 0x03C;
                if ((binaryValueNdx+2) < binaryValueLen) {
                    group3 = group3
                           | ((binaryValue[binaryValueNdx+2] >> 6) & 0x3);
                }
            } else {
                group3 = PAD_INDEX;
            }
            sb.append(BASE64EncodingString.charAt(group3));

            // Encode 4th 6-bit group
            int group4;
            if ((binaryValueNdx+2) < binaryValueLen) {
                group4 = binaryValue[binaryValueNdx+2] & 0x3F;
            } else {
                group4 = PAD_INDEX;
            }
            sb.append(BASE64EncodingString.charAt(group4));

            // After every MAX_GROUPS_PER_LINE groups, insert CR LF.
            // Unless this is the final line, in which case we skip that.
            groupsToEOL = groupsToEOL - 1;
            if (groupsToEOL == 0) {
                groupsToEOL = MAX_GROUPS_PER_LINE;
                if ((binaryValueNdx+3) <= binaryValueLen) {
                    sb.append(CR);
                    sb.append(LF);
                }
            }
        }
        return sb.toString();
    }