RSA加密工具类

package com.itech.kingdee.dssc.mdm.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
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.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.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.io.FileUtils;


public class RSAUtils {

	public static final String CHARSET = "UTF-8";
	public static final String RSA_ALGORITHM = "RSA";
	public static final String RSA_ALGORITHM_SIGN = "RSA";

	private  RSAPublicKey publicKey;
	private RSAPrivateKey privateKey;

	public RSAUtils(File publicKeyFile, File privateKeyFile) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
			String key = FileUtils.readFileToString(publicKeyFile, CHARSET);

			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64
					.decodeBase64(key.getBytes()));
			this.publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

			key = FileUtils.readFileToString(privateKeyFile, CHARSET);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64
					.decodeBase64(key.getBytes()));
			this.privateKey = (RSAPrivateKey) keyFactory
					.generatePrivate(pkcs8KeySpec);
		} catch (Exception e) {
			throw new RuntimeException("RSA初始化异常", e);
		}
	}
	public  String publicEncrypt(String data) {
		try {
			Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return StringUtils.newStringUtf8(Base64.encodeBase64(rsaSplitCodec(
					cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
					publicKey.getModulus().bitLength())));
		} catch (Exception e) {
			throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
		}
	}

	public String privateDecrypt(String data) {
		try {
			Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64
					.decodeBase64(data.getBytes()), publicKey.getModulus()
					.bitLength()), CHARSET);
		} catch (Exception e) {
			throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
		}
	}

	public String privateEncrypt(String data) {
		try {
			Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			return StringUtils.newStringUtf8(Base64.encodeBase64(rsaSplitCodec(
					cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
					publicKey.getModulus().bitLength())));
			// return Base64.encodeBase64String();
		} catch (Exception e) {
			throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
		}
	}

	public String publicDecrypt(String data) {
		try {
			Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			return StringUtils.newStringUtf8(rsaSplitCodec(cipher,
					Cipher.DECRYPT_MODE, Base64.decodeBase64(data.getBytes()),
					publicKey.getModulus().bitLength()));
			// return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE,
			// Base64.decodeBase64(data.getBytes()),
			// publicKey.getModulus().bitLength()), CHARSET);
		} catch (Exception e) {
			throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
		}
	}

	public static Map<String, String> generateKeyPair(String dir) {

		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
			// 密钥位数
			keyPairGen.initialize(2048);
			// 密钥对
			KeyPair keyPair = keyPairGen.generateKeyPair();
			// 公钥
			PublicKey publicKey = keyPair.getPublic();
			// 私钥
			PrivateKey privateKey = keyPair.getPrivate();
			// 得到公钥字符串
			String publicKeyString = getKeyString(publicKey);
			// 得到私钥字符串
			String privateKeyString = getKeyString(privateKey);
			// 将密钥对写入到文件
			FileUtils.writeStringToFile(new File(dir + "/publicKey.key"),
					publicKeyString, CHARSET);
			FileUtils.writeStringToFile(new File(dir + "/privateKey.key"),
					privateKeyString, CHARSET);
			// 将生成的密钥对返回
			Map<String, String> map = new HashMap<String, String>();
			map.put("publicKey", publicKeyString);
			map.put("privateKey", privateKeyString);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getKeyString(Key key) throws Exception {
		byte[] keyBytes = key.getEncoded();
		String s = StringUtils.newStringUtf8(Base64.encodeBase64(keyBytes));
		// String s = Base64.encodeBase64String(keyBytes);
		return s;
	}

	private static byte[] rsaSplitCodec(Cipher cipher, int opmode,
			byte[] datas, int keySize) throws IOException {
		int maxBlock = 0;
		if (opmode == Cipher.DECRYPT_MODE) {
			maxBlock = keySize / 8;
		} else {
			maxBlock = keySize / 8 - 11;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] buff;
		int i = 0;
		byte[] resultDatas = null;
		try {
			while (datas.length > offSet) {
				if (datas.length - offSet > maxBlock) {
					buff = cipher.doFinal(datas, offSet, maxBlock);
				} else {
					buff = cipher.doFinal(datas, offSet, datas.length - offSet);
				}
				out.write(buff, 0, buff.length);
				i++;
				offSet = i * maxBlock;
			}
			resultDatas = out.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
		} finally {
			out.close();
		}
		return resultDatas;
	}
}

读取JSON文件

	public void Test(){
		URL url = this.getClass().getResource("/tgvoucher/005.json");
		this.getRequestData(FileUtils.toFile(url);
	}
	private JSONObject getRequestData(File file) throws IOException {
		String content = FileUtils.readFileToString(file, "UTF-8");
		content = this.utils.publicEncrypt(content);
		JSONObject result = new JSONObject();
		result.put("data", content);
		return result;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值