package com.writeoff.security;

import org.junit.jupiter.api.Test;

import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import static org.junit.jupiter.api.Assertions.assertEquals;

class LoginPasswordCryptoServiceTest {

    private static final OAEPParameterSpec OAEP_SHA256_MGF1_SHA256 = new OAEPParameterSpec(
            "SHA-256",
            "MGF1",
            MGF1ParameterSpec.SHA256,
            PSource.PSpecified.DEFAULT
    );

    @Test
    void shouldUnwrapBrowserCompatibleEncryptedPassword() throws Exception {
        LoginPasswordCryptoService service = new LoginPasswordCryptoService();
        service.init();

        String rawPassword = "Abcd1234!";
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(
                new X509EncodedKeySpec(Base64.getDecoder().decode(service.getEncodedPublicKey()))
        );
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEP_SHA256_MGF1_SHA256);
        String encryptedPassword = LoginPasswordCryptoService.PASSWORD_PREFIX
                + Base64.getEncoder().encodeToString(cipher.doFinal(rawPassword.getBytes(StandardCharsets.UTF_8)));

        assertEquals(rawPassword, service.unwrapPassword(encryptedPassword));
    }

    @Test
    void shouldKeepPlainPasswordUntouched() {
        LoginPasswordCryptoService service = new LoginPasswordCryptoService();

        assertEquals("123456", service.unwrapPassword("123456"));
    }
}
