package com.malk.utils.crypto;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加密工具类 - 与德惠邮箱SSO文档保持一致
 */
public class RSACrypt {

    private static final String ALGORITHM = "RSA";
    private static final String CHARSET = "utf-8";

    /**
     * RSA公钥加密
     *
     * @param str       待加密字符串
     * @param publicKey Base64编码的RSA公钥
     * @return Base64编码的加密结果
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(ALGORITHM)
                .generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encrypted = cipher.doFinal(str.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * Base64字符串URL安全处理
     * + → *，/ → -，= → .
     *
     * @param base64String 原始Base64字符串
     * @return URL安全的字符串
     */
    public static String toUrlSafe(String base64String) {
        return base64String.replace('+', '*').replace('/', '-').replace('=', '.');
    }
}
