package cn.pluss.platform.klk;

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

public class LaKaLaUtility {
//   static String pubKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp5aV3ZiXG2R8Yd8Nxocv+cF7VAUHBc0TF4MNne7mI8wM2yEP2QgI+rK1qDf6G7\n" +
//            "ZFPhutpIHKQchpolbSuC0vgaHpSjO9OUs1fpnK/JjZq9o8DatUsA0n4Fccec9NBbV5dy5yrwro7xmDpsevp1\n" +
//            "/IeiIssi1+iD+nBWqqVFx7GVQIDAQAB";
    //测试公钥
    private static String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvO9EN9W6OG7y72VUWZili4m8DlD+TMofgIl96OPX9fRBS7Icg3oIqxmU20xFbiswJ2cCU6I1gbE7GDM14CihLQd26xW5T/8TmHCaVFFy1b9AWHNK7sW3aNd2KK1PI3h4gS38ND8jqvdr/8YZSCNF2KOoOe3F17FqVecBdq+1VZQIDAQAB";

    /**
     * 公钥解密
     * @param pubKey Base64 公钥
     * @param data Base64 数据
     * @return 解密字符串
     * @throws Exception 解密异常
     */
    public static String decrypt(String pubKey,String data){
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] keyBytes = decoder.decode(pubKey.getBytes());
            byte[] dataBytes = decoder.decode(data.getBytes());
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,
                    KeyFactory.getInstance("RSA").generatePublic(new
                            X509EncodedKeySpec(keyBytes)));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] cache;
            for (int i = 0, offset = 0, length = dataBytes.length; length -
                    offset > 0; i++, offset = i * 128) {
                if (length - offset > 128) {
                    cache = cipher.doFinal(dataBytes, offset, 128);
                } else {
                    cache = cipher.doFinal(dataBytes, offset, length - offset);
                }
                out.write(cache, 0, cache.length);
            }
            return out.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static  void main(String[] args){
        String key="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHB7j7gG3ioLnnr7bsuEXTAh/8YSxSp4lQIYGW9gX0Ikgz9JqARdg4iEnU6tgNirxA6Jdg0AWgLJQxQBEZMkwyK2ZfYgesYhlJkv6WVC8v5OkOrhA9NSQ3iS6JsYegsZO0GJSTtLQaTOF8WobPYe5NI+eWU1fRz2ZyxlWlKshBeQIDAQAB";
        String data="dPSiEm1MkN0mLs7boHPYscix5W8CpiwTssJe9eXyof+JrExCmSYJVCdqgIZfz/YZb58nYp9CxaOzYM3YgLfsUC226myZHrVDvzRIVm5C5Z14QBiy+RYrbC7WTQTRqtdJtl/C7zW7nZw2aTFnU7gxeXFOnwLgTMzrow83v39BQfCGW+mtjfXxxR5CJq79GSwLF3CiLB4Q2AVuDRlM0DN5HHtbfzktDm3QxyQ+mG/T/nqVH/DGgQTT8Rr5DK5wA2grybZXy9lcx0qJsqpKlpSCBzVKw6AQZ+bVa+qdzuCoswDAljDdaUEDFy5p081J7pMbpUoYsMRJyZ9zskLg02z9SA==";
        System.out.println(LaKaLaUtility.decrypt(key,data));
    }

}
