/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-impl
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.auth.basic.jpa.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.codec.digest.Sha2Crypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.auth.basic.jpa.api.entity.field.EncryptionAlgorithm;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

public class EncryptionHelper {

    private static final Logger LOG = LoggerFactory.getLogger(EncryptionHelper.class);

    static final String APR1_PREFIX = "$apr1$";
    static final String SHA512_PREFIX = "$6$";

    private EncryptionHelper() {
        throw new IllegalStateException("Utility class");
    }

    public static String encrypt(String plaintext, String cipher, String salt) throws NoSuchAlgorithmException {
        String passwordHash;

        if (EncryptionAlgorithm.MD5.equalsName(cipher)) {
            passwordHash = Md5Crypt.apr1Crypt((plaintext.getBytes(StandardCharsets.UTF_8)), salt);
            passwordHash = passwordHash.substring(passwordHash.lastIndexOf("$") + 1);
        } else if (EncryptionAlgorithm.SHA1.equalsName(cipher)) {
            passwordHash = Base64.encodeBase64String(
                    DigestUtils.sha1((plaintext + salt).getBytes(StandardCharsets.UTF_8)));
        } else if (EncryptionAlgorithm.SHA512.equalsName(cipher)) {
            passwordHash = Sha2Crypt.sha512Crypt((plaintext.getBytes(StandardCharsets.UTF_8)), SHA512_PREFIX + salt);
            passwordHash = passwordHash.substring(passwordHash.lastIndexOf("$"));
        } else if (EncryptionAlgorithm.PLAIN.equalsName(cipher)) {
            passwordHash = plaintext;
        } else {
            throw new NoSuchAlgorithmException();
        }

        return passwordHash;
    }

}
