package cn.yyxx.commsdk.core.utils;


import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SignUtils {

    private static final int MAX_ENCRYPT_BLOCK = 117;
    public static final String KEY_ALGORITHM = "RSA";



    public static String encryptRsaByPublicKey(String key, String text)
            throws Exception {

        // 对公钥解密
        byte[] data = Base64.decode(key, Base64.NO_WRAP);



        byte[] byteText = text.getBytes();
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(data);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        int inputLen = byteText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen -offSet > 0 ){
            if(inputLen -offSet >MAX_ENCRYPT_BLOCK){
                cache = cipher.doFinal(byteText,offSet,MAX_ENCRYPT_BLOCK);
            }else{
                cache = cipher.doFinal(byteText,offSet,inputLen - offSet);
            }
            out.write(cache,0,cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();


        String strBase64 = new String(Base64.encode(encryptedData, Base64.NO_WRAP));

        return strBase64;
    }


}

