001/**
002 *
003 * Copyright © 2014-2021 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.util.stringencoder.android;
018
019import java.nio.charset.StandardCharsets;
020
021import org.jivesoftware.smack.util.stringencoder.StringEncoder;
022
023import android.util.Base64;
024
025/**
026 * An URL-safe Base64 encoder.
027 * @author Florian Schmaus
028 */
029public final class AndroidBase64UrlSafeEncoder implements StringEncoder<String> {
030
031    /**
032     * An instance of this encoder.
033     */
034    public static AndroidBase64UrlSafeEncoder INSTANCE = new AndroidBase64UrlSafeEncoder();
035
036    private static final int BASE64_ENCODER_FLAGS = Base64.URL_SAFE | Base64.NO_WRAP;
037
038    private AndroidBase64UrlSafeEncoder() {
039        // Use getInstance()
040    }
041
042    @Override
043    public String encode(String string) {
044        return Base64.encodeToString(string.getBytes(StandardCharsets.UTF_8), BASE64_ENCODER_FLAGS);
045    }
046
047    @Override
048    public String decode(String string) {
049        byte[] bytes = Base64.decode(string, BASE64_ENCODER_FLAGS);
050        return new String(bytes, StandardCharsets.UTF_8);
051    }
052
053}