package com.gh.common.util;

import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class RSEUtils {

	/**
	 * 公钥
	 */
	private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQConqikyOCl5f/VO/vZ+s6wVOhFJcI7o7hYvaLQ5Lzt5/HXbozTeRrGonKFPJurapf9hzjkg0F4/BNFMGXRVlReVdwh+Px5rbXU/ceikF8Ouf67qxiGAuDVC+4e3eIHh+mH68DlqWFJ78sB80iSLXelflGuHkbTOTtaC5F2l+AgxQIDAQAB";

	/**
	 * 加密算法RSA
	 */
	private static final String KEY_ALGORITHM = "RSA";

	/**
	 * 得到公钥
	 * 
	 * @return PublicKey 公钥
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	private static PublicKey getPublicKeyFromX509() throws Exception {
		byte[] decodedKey = Base64.decode(PUBLIC_KEY, Base64.DEFAULT);
		X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return keyFactory.generatePublic(x509);
	}

	/**
	 * 使用公钥加密
	 * 
	 * @param content
	 * @return
	 */
	public static String encryptByPublic(String content) {
		try {
			PublicKey pubkey = getPublicKeyFromX509();

			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, pubkey);

			byte[] data = content.getBytes("UTF-8");
			byte[] output = cipher.doFinal(data);

			String s = new String(Base64.encode(output, Base64.DEFAULT));

			return s;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 使用公钥解密
	 * 
	 * @param content 密文
	 * @return 解密后的字符串
	 */
	public static String decryptByPublic(String content) {
		try {
			PublicKey pubkey = getPublicKeyFromX509();
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.DECRYPT_MODE, pubkey);
			InputStream ins = new ByteArrayInputStream(Base64.decode(content,
					Base64.DEFAULT));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[128];
			int len;
			while ((len = ins.read(buffer)) != -1) {
				byte[] block = null;
				if (buffer.length == len) {
					block = buffer;
				} else {
					block = new byte[len];
					for (int i = 0; i < len; i++) {
						block[i] = buffer[i];
					}
				}
				baos.write(cipher.doFinal(block));
			}
			return new String(baos.toByteArray(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
