001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the License.
004 *
005 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
006 * specific language governing permission and limitations under the License.
007 *
008 * When distributing Covered Software, include this CDDL Header Notice in each file and include
009 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
010 * Header, with the fields enclosed by brackets [] replaced by your own identifying
011 * information: "Portions copyright [year] [name of copyright owner]".
012 *
013 * Copyright 2015 ForgeRock AS.
014 */
015
016package org.forgerock.util.encode;
017
018/**
019 * Makes use of the very fast and memory efficient Base64 class to encode and
020 * decode to and from BASE64 in full accordance with RFC 2045. And then replaces
021 * + and / for - and _ respectively and removes the padding character = to be in
022 * accordance with RFC 4648.
023 */
024public final class Base64url {
025    /**
026     * Decodes the given Base64url encoded String into a byte array.
027     *
028     * @param content
029     *            The Base64url encoded String to decode.
030     * @return The decoded byte[] array.
031     */
032    public static byte[] decode(final String content) {
033        final StringBuilder builder =
034                new StringBuilder(content.replaceAll("-", "+").replaceAll("_", "/"));
035        final int modulus = builder.length() % 4;
036        final int numberOfPaddingChars = 4 - modulus;
037        if (modulus != 0) {
038            for (int i = 0; i < numberOfPaddingChars; i++) {
039                builder.append('=');
040            }
041        }
042        return Base64.decode(builder.toString());
043    }
044
045    /**
046     * Encodes the given byte array into a Base64url encoded String.
047     *
048     * @param content
049     *            The byte array to encode.
050     * @return The Base64url encoded byte array.
051     */
052    public static String encode(final byte[] content) {
053        return Base64.encode(content).replaceAll("\\+", "-").replaceAll("/", "_").replaceAll("=",
054                "");
055    }
056
057    private Base64url() {
058        // No impl.
059    }
060}