前段时间咱老大吩咐我写一个rsa前台加密到后台用java解密。(说实话这之前我还真没用过)
不过没办法啊,这是任务,于是研究了一下。圆满完成任务了,下面共享下实现思路:
准备工作:其实鄙人也没那么强啦,第三方包是必须的
bcprov-jdk15on-148.jar
commons-codec-1.7.jar
commons-lang-2.4.jar
log4j-1.2.15.jar
slf4j-api-1.6.1.jar
//关键工具类
package com.web.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.Provider;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import javax.crypto.Cipher;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
/**
* RSA算法加密/解密工具类。
*
* @author fuchun
* @version 1.0.0, 2010-05-05
*/
public abstract class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
/** 算法名称 */
private static final String ALGORITHOM = "RSA";
/**保存生成的密钥对的文件名称。 */
private static final String RSA_PAIR_FILENAME = "/__RSA_PAIR.txt";
/** 密钥大小 */
private static final int KEY_SIZE = 1024;
/** 默认的安全服务提供者 */
private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
private static KeyPairGenerator keyPairGen = null;
private static KeyFactory keyFactory = null;
/** 缓存的密钥对。 */
private static KeyPair oneKeyPair = null;
private static File rsaPairFile = null;
static {
try {
keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
} catch (NoSuchAlgorithmException ex) {
LOGGER.error(ex.getMessage());
}
rsaPairFile = new File(getRSAPairFilePath());
}
private RSAUtils() {
}
/**
* 生成并返回RSA密钥对。
*/
private static synchronized KeyPair generateKeyPair() {
try {
keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(),"yyyyMMdd").getBytes()));
oneKeyPair = keyPairGen.generateKeyPair();
saveKeyPair(oneKeyPair);
return oneKeyPair;
} catch (InvalidParameterException ex) {
LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
} catch (NullPointerException ex) {
LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.",
ex);
}
return null;
}
/**
* 返回生成/读取的密钥对文件的路