RSA 加密算法(分组加密,分组解密)

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.lang.ArrayUtils;

/**
 * RSA加密与解密,采用Base64编码
 *
 * @author East271536394
 * @version 2012-6-25 上午9:18:57
 */
public class RSAProvider {

    /**
     * KEY_ALGORITHM
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 加密Key的长度等于1024或者2048
     */
    public static int KEYSIZE = 1024;
    /**
     * 解密时必须按照此分组解密
     */
    public static int decodeLen = KEYSIZE / 8;
    /**
     * 加密时小于117即可
     */
    public static int encodeLen = 100;
    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "publicKey";
    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "privateKey";
    /**
     * MODULES
     */
    private static final String MODULES = "RSAModules";

    /**
     * 
     * 生成KeyPair
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static Map<String, Object> generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(KEYSIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥   
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // 私钥   
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        BigInteger modules = privateKey.getModulus();

        Map<String, Object> keys = new HashMap<String, Object>(3);
        keys.put(PUBLIC_KEY, publicKey);
        keys.put(PRIVATE_KEY, privateKey);
        keys.put(MODULES, modules);
        return keys;
    }

    /**
     * 
     * 加密private key
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static byte[] encryptPrivateKey(String data, String key) throws Exception {
        byte[] bytes = data.getBytes("UTF-8");
        byte[] encode = new byte[] {};
        for (int i = 0; i < bytes.length; i += encodeLen) {
            byte[] subarray = ArrayUtils.subarray(bytes, i, i + encodeLen);
            byte[] doFinal = encryptByPrivateKey(subarray, key);
            encode = ArrayUtils.addAll(encode, doFinal);
        }
        return encode;
    }

    /**
     * 解密 public key
     * 方法说明。
     * @param encode
     * @param key
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static String decryptPublicKey(byte[] encode, String key) throws Exception {
        byte [] buffers = new byte[]{};
        for (int i = 0; i < encode.length; i += decodeLen) {
            byte[] subarray = ArrayUtils.subarray(encode, i, i + decodeLen);
            byte[] doFinal = decryptByPublicKey(subarray, key);
            buffers = ArrayUtils.addAll(buffers, doFinal);    
        }
        return new String(buffers, "UTF-8");
    }

    /**
     * 
     * 加密public key
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static byte[] encryptPublicKey(String data, String key) throws Exception {
        byte[] bytes = data.getBytes("UTF-8");
        byte[] encode = new byte[] {};
        for (int i = 0; i < bytes.length; i += encodeLen) {
            byte[] subarray = ArrayUtils.subarray(bytes, i, i + encodeLen);
            byte[] doFinal = encryptByPublicKey(subarray, key);
            encode = ArrayUtils.addAll(encode, doFinal);
        }
        return encode;
    }

    /**
     * 解密 private key
     * 方法说明。
     * @param encode
     * @param key
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static String decryptPrivateKey(byte[] encode, String key) throws Exception {
        byte [] buffers = new byte[]{};
        for (int i = 0; i < encode.length; i += decodeLen) {
            byte[] subarray = ArrayUtils.subarray(encode, i, i + decodeLen);
            byte[] doFinal = decryptByPrivateKey(subarray, key);
            buffers = ArrayUtils.addAll(buffers, doFinal);
        }
        return new String(buffers, "UTF-8");
    }

    /**
     * 用私钥解密 
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     * @author East271536394
     */
    private static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
        // 对密钥解密  取得私钥  
        byte[] keyBytes = Base64.base64ToByte(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 对数据解密   
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }

    /**
     *  
     * 用公钥解密 
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     * @author East271536394
     */
    private static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {
        // 对密钥解密   取得公钥 
        byte[] keyBytes = Base64.base64ToByte(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据解密   
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**
     * 
     * 用公钥加密 
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     * @author East271536394
     */
    private static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        // 对公钥解密   
        // 取得公钥  
        byte[] keyBytes = Base64.base64ToByte(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密   
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**
     * 用私钥加密 
     * 
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     * @author East271536394
     */
    private static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception {
        // 对密钥解密   
        // 取得私钥  
        byte[] keyBytes = Base64.base64ToByte(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 对数据加密   
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }

    /**
     * 
     * 
     * @return
     * @author East271536394
     */
    public static byte[] getModulesBytes(Map<String, Object> keys) {
        BigInteger big = (BigInteger) keys.get(MODULES);
        return big.toByteArray();

    }

    /**
     * 
     * 取得私钥 
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static String getPrivateKeyBytes(Map<String, Object> keys) throws Exception {
        Key key = (Key) keys.get(PRIVATE_KEY);
        return Base64.byteToBase64(key.getEncoded());
    }

    /**
     * 取得公钥 
     * 
     * @return
     * @throws Exception
     * @author East271536394
     */
    public static String getPublicKeyBytes(Map<String, Object> keys) throws Exception {
        Key key = (Key) keys.get(PUBLIC_KEY);
        return Base64.byteToBase64(key.getEncoded());
    }

}

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {
	/**
	 * 转为base64
	 * @param s 原始字符串
	 * @return String base64
	 */
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		try {
			return (new BASE64Encoder()).encode(s.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从base64还原
	 * @param s base64串
	 * @return String 原始串
	 */
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 从byte转到base64
	 * @param bs 原始串
	 * @return String base64串
	 */
	public static String byteToBase64(byte[] bs) {
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bs);
	}

	/**
	 * 从base64转到byte
	 * @param base64 base64串
	 * @return byte 原始串
	 */
	public static byte[] base64ToByte(String base64) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return decoder.decodeBuffer(base64);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}





版权声明:本文为East271536394原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。