Rsa加解密

package com.gzxf.utils;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;


/**
 * RSA
 *
 */
@SuppressWarnings("restriction")
public class RSAHelper {
	public static int keySize = 2048;
	public static String charset = "UTF-8";

	/**
	 * To byte array byte [ ].
	 *
	 * @param hexString the hex string
	 * @return the byte [ ]
	 */
	public static byte[] toByteArray(String hexString) {
		if (hexString == null || hexString.isEmpty())
			return null;
		hexString = hexString.toLowerCase();
		final byte[] byteArray = new byte[hexString.length() >> 1];
		int index = 0;
		for (int i = 0; i < hexString.length(); i++) {
			if (index  > hexString.length() - 1)
				return byteArray;
			byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
			byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
			byteArray[i] = (byte) (highDit << 4 | lowDit);
			index += 2;
		}
		return byteArray;
	}


	/**
	 * byte[] to Hex string.
	 *
	 * @param byteArray the byte array
	 * @return the string
	 */
	public static String toHexString(byte[] byteArray) {
		final StringBuilder hexString = new StringBuilder("");
		if (byteArray == null || byteArray.length <= 0)
			return null;
		for (int i = 0; i < byteArray.length; i++) {
			int v = byteArray[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				hexString.append(0);
			}
			hexString.append(hv);
		}
		return hexString.toString().toLowerCase();
	}

	/**
	 * 得到公钥
	 *
	 * @param key
	 *            密钥字符串(经过base64编码)
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = toByteArray(key);

		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	/**
	 * 得到私钥
	 *
	 * @param key
	 *            密钥字符串(经过base64编码)
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = toByteArray(key);

		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	/**
	 * 得到密钥字符串(经过hex编码)
	 *
	 * @return
	 */
	public static String getKeyString(Key key) throws Exception {
		byte[] keyBytes = key.getEncoded();
		String s = toHexString(keyBytes);
		return s;
	}

	public static byte[] byteMerger(byte[] bt1, byte[] bt2) {
		if(bt2 == null) return bt1;
		if(bt1 == null) return bt2;
		byte[] bt3 = new byte[bt1.length+bt2.length];
		System.arraycopy(bt1, 0, bt3, 0, bt1.length);
		System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
		return bt3;
	}

	public static byte[] subArray(byte[] byte_array, int off, int len) {
		byte[] result = new byte[len];
		System.arraycopy(byte_array, off, result, 0, len); //源数组,起始位置,目的数组,起始位置,长度
		return result;
	}

	/**
	 * 加密的核心步骤
	 *
	 * @param src
	 *            如果src.getBytes("UTF-8").length > 117那么加密就会报错!需要做迭代处理。
	 * @param cipher
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptFinal(byte[] src, Cipher cipher) throws Exception {
		byte[] enBytes = null;
		int len = src.length;
		int limit = keySize / 8 - 11;
		if (len > limit) {
			int remainder = len % limit;
			int divisor = len / limit;
			/*
			 * 整除数处理 处理以117为倍数的单元
			 */
			for (int i = 0; i < divisor; i++) {
				byte[] subEnBytes = cipher.doFinal(src, limit * i, limit);
				enBytes = byteMerger(enBytes, subEnBytes);
			}
			/*
			 * 余数处理 处理不足117的单元
			 */
			if (remainder > 0) {
				byte[] subEnBytes = cipher.doFinal(src, limit * divisor,
						remainder);
				enBytes = byteMerger(enBytes, subEnBytes);
			}
		} else {
			enBytes = cipher.doFinal(src);
		}
		return enBytes;
	}

	/**
	 * 解密的核心步骤
	 *
	 * @param src
	 *            如果src.length > keySize / 8那么就会报错!需要迭代处理。
	 * @param cipher
	 * @return
	 * @throws Exception
	 */
	private static byte[] decryptFinal(byte[] src, Cipher cipher) throws Exception {
		byte[] deBytes = null;
		int len = src.length;
		int limit = keySize / 8;
		if (len > limit) {
			int remainder = len % limit;
			int divisor = len / limit;
			/*
			 * 整除数处理 处理以128为倍数的单元
			 */
			for (int i = 0; i < divisor; i++) {
				byte[] subDeBytes = subArray(src, limit * i, limit);
				deBytes = byteMerger(deBytes, cipher.doFinal(subDeBytes));
			}
			/*
			 * 余数处理 处理不足keySize / 8的单元
			 * NOTE:在解密的时候都是以keySize / 8为一个单元,尚未发现例外。所以这个步骤不会执行,留下它以防万一吧。
			 */
			if (remainder > 0) {
				byte[] subDeBytes = subArray(src, limit * divisor, remainder);
				deBytes = byteMerger(deBytes, cipher.doFinal(subDeBytes));
			}
		} else {
			deBytes = cipher.doFinal(src);
		}
		/*
		 * 如果是“RSA/ECB/NoPadding”模式,需要将(byte)0去掉
		 */
		if (true) {
			byte[] deBytesWithOutZero = null;
			for (int i = 0; i < deBytes.length; i++) {
				if (deBytes[i] == (byte) 0) {
					continue;
				} else {
					byte[] cur = new byte[1];
					cur[0] = deBytes[i];
					deBytesWithOutZero = byteMerger(deBytesWithOutZero, cur);
				}
			}
			return deBytesWithOutZero;
		}
		return deBytes;
	}

	public static void main(String[] args) throws Exception {

		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		// 密钥位数
		keyPairGen.initialize(RSAHelper.keySize);
		// 密钥对
		KeyPair keyPair = keyPairGen.generateKeyPair();

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

		// 私钥
		PrivateKey privateKey = keyPair.getPrivate();

		String publicKeyString = getKeyString(publicKey);
		System.out.println("public:\n" + publicKeyString);

		String privateKeyString = getKeyString(privateKey);
		System.out.println("private:\n" + privateKeyString);

		// 保存密钥对,并将私钥用来分发给各个APP开发商家

		// 加解密类
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");// Cipher.getInstance("RSA/ECB/PKCS1Padding");  NoPadding

		// 明文
		String strPlainText = "我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!";
		strPlainText += "我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!我们都很好!";
		strPlainText += "OK!";
		byte[] plainText = strPlainText.getBytes(charset);

		// 加密
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] enBytes = encryptFinal(plainText, cipher);
		//byte[] enBytes = cipher.doFinal(plainText);
		System.out.println("plainText:" + strPlainText);
		System.out.println("plainHex:" + toHexString(plainText));
		System.out.println("enBYTES:" + new String(enBytes));
		System.out.println("enHEX:" + toHexString(enBytes));

		// 通过密钥字符串得到密钥
		publicKey = getPublicKey(publicKeyString);
		privateKey = getPrivateKey(privateKeyString);

		String hexStr = toHexString(enBytes);
		byte[] gotEnBytes = toByteArray(hexStr);

		// 解密
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] deBytes = decryptFinal(gotEnBytes, cipher);
		//byte[] deBytes = cipher.doFinal(enBytes);

		publicKeyString = getKeyString(publicKey);
		System.out.println("public:\n" + publicKeyString);

		privateKeyString = getKeyString(privateKey);
		System.out.println("private:\n" + privateKeyString);

		String s = new String(deBytes, charset);
		System.out.println(s);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值