package com.csair.rsa;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.security.Key;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
/**
* @Description: rsa算法--加密and解密
* @author: ppt
* @date: 2014-3-6 下午7:38:40
*/
public class RSAUtil {
/**
* @Description: 加密
* @author: ppt
* @param key
* @param src
* @throws Exception
* @return: String
*/
public String encrypt(Key key, String src) throws Exception {
try {
byte[] data = src.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
i++;
}
return toHexString(raw);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* @Description: 解密
* @author: ppt
* @param key
* @param cipherText
* @throws Exception
* @return: String
*/
public String decrypt(Key key, String cipherText) throws Exception {
try {
byte[] raw = hexStringToBytes(cipherText);
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return new String(bout.toByteArray(),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* @Description: 读取密钥
* @author: ppt
* @param fileName
* @throws Exception
* @return: Object
*/
public Object readFromFile(String fileName) throws Exception {
ObjectInputStream input = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream(fileName));
Object obj = input.readObject();
input.close();
return obj;
}
private String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 测试
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RSAUtil rsa = new RSAUtil();
RSAPublicKey pubKey = (RSAPublicKey) rsa.readFromFile("public_key.dat");
RSAPrivateKey priKey = (RSAPrivateKey) rsa.readFromFile("private_key.dat");
String str = "i love you";
//加密
String miwen = rsa.encrypt(pubKey,str);
System.out.println("length==" + miwen.length());
System.out.println("加密后==" + miwen);
//解密
String mingwen = rsa.decrypt(priKey, miwen);
System.out.println("解密后==" + mingwen);
}
}
生成密钥方法:
package com.csair.rsa;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* @Description: 随机生成RSA密钥
* @author: ppt
* @date: 2014-3-6 下午7:54:26
*/
public class KeyRSA {
private KeyPairGenerator kpg = null;
private KeyPair kp = null;
private PublicKey public_key = null;
private PrivateKey private_key = null;
private FileOutputStream public_file_out = null;
private ObjectOutputStream public_object_out = null;
private FileOutputStream private_file_out = null;
private ObjectOutputStream private_object_out = null;
/**
* 构造函数
* @param in 指定密匙长度(取值范围:512~2048)
* @throws Exception 异常
*/
public KeyRSA(int in, String publicKeyPath,String privateKeyPath) throws Exception {
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(in); //指定密匙长度(取值范围:512~2048)
kp = kpg.genKeyPair();
public_key = kp.getPublic(); //获得公匙
private_key = kp.getPrivate(); //获得私匙
//保存公匙
public_file_out = new FileOutputStream(publicKeyPath);
public_object_out = new ObjectOutputStream(public_file_out);
public_object_out.writeObject(public_key);
public_object_out.flush();
public_object_out.close();
public_file_out.close();
//保存私匙
private_file_out = new FileOutputStream(privateKeyPath);
private_object_out = new ObjectOutputStream(private_file_out);
private_object_out.writeObject(private_key);
private_object_out.flush();
private_object_out.close();
private_file_out.close();
}
public static void main(String[] args) {
try {
String publicKeyPath = "C:\\Users\\ppt\\Desktop\\test\\public_key.dat";
String privateKeyPath = "C:\\Users\\ppt\\Desktop\\test\\private_key.dat";
new KeyRSA(2048, publicKeyPath, privateKeyPath);
System.out.println("ok");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}