package cn.iocoder.yudao.module.pms.oa;

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

public class E9ApiTokenUtil {
    public static String encryptString(String pubkey, String plaintext) {
        PublicKey publicKey = null;
        try {
            publicKey = getFromBase64String(pubkey);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        if (publicKey == null || plaintext == null) {
            return null;
        }
        byte[] data = plaintext.getBytes();
        try {
            byte[] en_data = encrypt(publicKey, data);
            return Base64.getEncoder().encodeToString(en_data);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    public static PublicKey getFromBase64String(String publicKeyString) throws
            Exception {
        byte[] keyBytes = publicKeyString.getBytes();
        byte[] ks = Base64.getDecoder().decode(keyBytes);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(ks);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
    public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
        Cipher ci = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        ci.init(Cipher.ENCRYPT_MODE, publicKey);
        return ci.doFinal(data);
    }
}
