Java原生实现RSA非对称加加密,源码参考:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;
public class RSAUtil {
/** 换行符 **/
private final static String lineSeparator = System.getProperty("line.separator", "\n");
/** 加解密算法键值-这里RSA **/
private final static String KEY_ALGORITHM = "RSA";
/** 获取公钥的KEY **/
public final static String PUBLIC_KEY = "RSAPublicKey";
/** 获取私钥的KEY **/
public final static String PRIVATE_KEY = "RSAPrivateKey";
/**
* 生成RSA算法的密钥对
*
* @return 密钥对,Map-> key=RSAPublicKey|KEY=RSAPrivateKey
* @throws NoSuchAlgorithmException
* 获取密钥对可能发生的异常
*/
public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator kGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
// init the keyPair
KeyPair keyPair = kGenerator.generateKeyPair();
// get public key
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// get private key
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keys = new HashMap<String, Object>();
keys.put(PUBLIC_KEY, publicKey);
keys.put(PRIVATE_KEY, privateKey);
return keys;
}
/**
* 加密
*
* @param key
* 加密使用的[公钥/私钥]
* @param input
* 需要加密的明文
* @return 加密后的密文
* @throws Exception
* 加密过程中可能发生的异常
*/
public static byte[] encrypt(Key key, byte[] input) throws Exception {
if (key != null) {
// Cipher负责完成加密或解密工作,基于RSA
Cipher cipher;
try {
cipher = Cipher.getInstance(KEY_ALGORITHM);
// 根据公钥,对Cipher对象进行初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] resultBytes = cipher.doFinal(input);
return resultBytes;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法:" + e.getMessage());
} catch (NoSuchPaddingException e) {
throw new Exception("加密过程中发生异常:" + e.getMessage());
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查:" + e.getMessage());
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法:" + e.getMessage());
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏:" + e.getMessage());
}
} else {
throw new Exception("解密私钥为空, 请设置");
}
}
/**
* 解密
*
* @param key
* 对应解密的[公钥或私钥]
* @param input
* 需要解密的加密信息
* @return 解密后的明文信息
* @throws Exception
* 解密过程中可能发生的异常
*/
public static byte[] decrypt(Key key, byte[] input) throws Exception {
if (key == null) {
throw new Exception("解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// Cipher负责完成加密或解密工作,基于RSA
cipher = Cipher.getInstance(KEY_ALGORITHM);
// 根据私钥,对Cipher对象进行初始化
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] output = cipher.doFinal(input);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法:" + e.getMessage());
} catch (NoSuchPaddingException e) {
throw new Exception("解密过程中发生异常:" + e.getMessage());
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查:" + e.getMessage());
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法:" + e.getMessage());
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏:" + e.getMessage());
}
}
/**
* 通过文件获取私钥对象
*
* @param file
* 私钥文件
* @return 私钥对象
* @throws Exception
* 从文件私钥获取私钥Java对象过程中可能发生的异常
*/
public static PrivateKey getPrivateKey(File file) throws Exception {
String strPrivateKey = null;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
sb.append(lineSeparator);
}
br.close();
// 字符
strPrivateKey = sb.toString().substring(0, sb.toString().length() - lineSeparator.length());
} catch (IOException e) {
throw new Exception("私钥数据流读取错误:" + e.getMessage());
}
try {
byte[] buffer = Base64.decodeBase64(strPrivateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("=====无此算法=====");
} catch (InvalidKeySpecException e) {
throw new Exception("=====密钥非法=====");
} catch (NullPointerException e) {
throw new Exception("=====私钥数据为空=====");
}
}
/**
* 通过字符串获取私钥对象
*
* @param strPrivateKey
* 字符串的私钥
* @return 私钥对象
* @throws Exception
* 从字符串私钥获取私钥Java对象过程中可能发生的异常
*/
public static PrivateKey getPrivateKey(String strPrivateKey) throws Exception {
try {
byte[] buffer = Base64.decodeBase64(strPrivateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("=====无此算法=====");
} catch (InvalidKeySpecException e) {
throw new Exception("=====密钥非法=====");
} catch (NullPointerException e) {
throw new Exception("=====私钥数据为空=====");
}
}
/**
* 从公钥文件中加载获取公钥Java对象
*
* @param file
* 公钥文件
* @return Java公钥对象
* @throws Exception
* 获取过程中可能发生的异常
*/
public static PublicKey getPublicKey(File file) throws Exception {
String strRSAPublicKey = null;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
sb.append(lineSeparator);
}
br.close();
strRSAPublicKey = sb.toString().substring(0, sb.toString().length() - lineSeparator.length());
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输入流为空");
}
try {
byte[] buffer = Base64.decodeBase64(strRSAPublicKey.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("=====无此算法=====");
} catch (InvalidKeySpecException e) {
throw new Exception("=====公钥非法=====");
} catch (NullPointerException e) {
throw new Exception("=====公钥数据为空=====");
}
}
/**
* 从公钥字符串加载获取公钥Java对象
*
* @param strPublicKey
* 公钥字符串
* @return Java公钥对象
* @throws Exception
* 获取过程中可能发生的异常
*/
public static PublicKey getPublicKey(String strPublicKey) throws Exception {
try {
byte[] buffer = Base64.decodeBase64(strPublicKey.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("=====无此算法=====");
} catch (InvalidKeySpecException e) {
throw new Exception("=====公钥非法=====");
} catch (NullPointerException e) {
throw new Exception("=====公钥数据为空=====");
}
}
/**
* 将Java对象的公钥或者私钥转换为字符串
*
* @param key
* 公钥/私钥
* @return 秘钥的字符串
*/
public static String key2String(Key key) {
byte[] keyBytes = key.getEncoded();
String result = new String(Base64.encodeBase64(keyBytes));
return result;
}
}
over ,搞定收工!
http://blog.xqlee.com/article/16.html