package com.ai.da.common.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * Rsa加密工具
 */
public class RsaEncryptUtils {

    /**
     * 加密方法
     *
     * @param content   需要加密的内容
     * @param publicKey 公钥
     * @return 加密后得到的字符串
     * @throws Exception
     */
    public static String encrypt(String content, String publicKey) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKeyText = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKeyText);
        byte[] result = doLongerCipherFinal(cipher, content.getBytes());
        return Base64.encodeBase64String(result);
    }

    private static byte[] doLongerCipherFinal(Cipher cipher, byte[] source) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        int totalSize = source.length;
        while (totalSize - offset > 0) {
            int size = Math.min(cipher.getOutputSize(0) - 11, totalSize - offset);
            out.write(cipher.doFinal(source, offset, size));
            offset += size;
        }
        out.close();
        return out.toByteArray();
    }
}
