JAVA中RSA加密和解密
公钥加密-私钥解密
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAUtil {
private static KeyPairGenerator kpg = null;
//密钥长度
private static int keyLen=1024;
private static KeyPair kp = null;
private static PublicKey public_key = null;
private static PrivateKey private_key = null;
private static String publicKey = "";
private static String privateKey = "";
//加密工具
private static Cipher encryptCipher = null;
//解密工具
private static Cipher decryptCipher = null;
static{
try {
if(getPubKeyStrFromFile().isEmpty()||getPrivateKeyStrFromFile().isEmpty()){
createKeyPair();
publicKey = getPubKeyStr();
privateKey = getPrivateKeyStr();
}else{
publicKey = getPubKeyStrFromFile();
privateKey = getPrivateKeyStrFromFile();
}
initEncryptCipher();
initDencryptCipher();
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
public static String getPubKey(){
return publicKey;
}
private static void createKeyPair(){
try{
kpg = KeyPairGenerator.getInstance("RSA"); // 创建‘密匙对’生成器
kpg.initialize(keyLen); // 指定密匙长度(取值范围:512~2048)
kp = kpg.genKeyPair(); // 生成‘密匙对’,其中包含着一个公匙和一个私匙的信息
public_key = kp.getPublic(); // 获得公匙
private_key = kp.getPrivate(); // 获得私匙
PropertiesConfigService instance = PropertiesConfigService.getInstance();
instance.setProperty("public_key", getPubKeyStr());
instance.setProperty("private_key", getPrivateKeyStr());
}catch(NoSuchAlgorithmException ex){
LOG.error(ex.getMessage());
}
catch(NoSuchPaddingException ex){
LOG.error(ex.getMessage());
}
catch(InvalidKeyException ex){
LOG.error(ex.getMessage());
}catch (Exception ex) {
LOG.error(ex.getMessage());
}
}
/**
* 从文件中读取公钥
* @return PublicKey
*/
public static PublicKey getPubKeyFromFile() {
BASE64Decoder b64d = new BASE64Decoder();
try {
byte[] keyByte = b64d.decodeBuffer(publicKey);
X509EncodedKeySpec x509ek = new X509EncodedKeySpec(keyByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509ek);
return publicKey;
}catch (IOException e) {
LOG.error(e.getMessage());
}catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
}catch (InvalidKeySpecException e) {
LOG.error(e.getMessage());
}
return null;
}
/**
* 从文件中读取密钥
* @return PrivateKey
*/
public static PrivateKey getPrivateKeyFromFile() {
try{
BASE64Decoder b64d = new BASE64Decoder();
byte[] keyByte = b64d.decodeBuffer(privateKey);
PKCS8EncodedKeySpec s8ek = new PKCS8EncodedKeySpec(keyByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(s8ek);
return privateKey;
}
catch(FileNotFoundException ex){
LOG.error(ex.getMessage());
}
catch(IOException ex){
LOG.error(ex.getMessage());
}
catch(NoSuchAlgorithmException ex){
LOG.error(ex.getMessage());
}
catch(InvalidKeySpecException ex){
LOG.error(ex.getMessage());
}
return null;
}
public static void initEncryptCipher() throws Exception {
encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE,getPubKeyFromFile());
}
public static void initDencryptCipher() throws Exception {
decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, getPrivateKeyFromFile());
}
/**
* 获取公钥字符串
* @return
*/
public static String getPubKeyStr(){
sun.misc.BASE64Encoder b64 = new sun.misc.BASE64Encoder();
return b64.encode(public_key.getEncoded());
}
/**
* 获取密钥字符串
* @return
*/
public static String getPrivateKeyStr(){
sun.misc.BASE64Encoder b64 = new sun.misc.BASE64Encoder();
return b64.encode(private_key.getEncoded());
}
/**
* 从文件中讀取公钥
* @return
*/
public static String getPubKeyStrFromFile() {
String getPbKey = PropertiesConfigService.getInstance().
getString("public_key","");
return getPbKey;
}
/**
* 从文件中讀取密钥
* @return
*/
public static String getPrivateKeyStrFromFile() {
String getPvKey = PropertiesConfigService.getInstance().
getString("private_key","");
return getPvKey;
}
/**
* 加密
* @param source
* @return
* @throws Exception
*/
public static String encrypt(String source) throws Exception {
byte[] sbt = source.getBytes();
byte[] epByte = encryptCipher.doFinal(sbt);
BASE64Encoder encoder = new BASE64Encoder();
String epStr = encoder.encode(epByte);
return epStr;
}
/**
* 解密
* @param cryptograph
* @return
* @throws Exception
*/
public static String decrypt(String cryptograph) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
byte[] b1 = decoder.decodeBuffer(cryptograph);
byte[] b = decryptCipher.doFinal(b1);
return new String(b);
}
}
测试类
public class Test {
public static void main(String[] args) throws Exception {
String pub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwFBsQXkoPNIFAhD55AAxZAw2ccGUWZWyb1Vpm"+
"rCK2eJnaLywJvu+X2g6zMUg+XF1CnuqLYw5daiWohBUaiQe9sBD4irAgds6l11EA7KEyUTO2FdLf"+
"RiF3Jfbu6bbqRVsPI5Zz4t9mNeypLbI1Bn/Rf3KD8p+h6uTfgFYzjzaqQQIDAQAB";//此处假设为公钥
Cipher encryptCipher = null;
BASE64Decoder b64d = new BASE64Decoder();
byte[] keyByte = b64d.decodeBuffer(pub);
X509EncodedKeySpec x509ek = new X509EncodedKeySpec(keyByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509ek);
encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE,publicKey);
String source = "123456";
byte[] sbt = source.getBytes();
byte[] epByte = encryptCipher.doFinal(sbt);
BASE64Encoder encoder = new BASE64Encoder();
String epStr = encoder.encode(epByte);
System.out.println(epStr);
}
}