您的位置:

java中rsa使用简述(rsa是基于)

本文目录一览:

怎样用Java实现RSA加密

提供加密,解密,生成密钥对等方法。�梢愿�模��遣灰��螅�裨蛐�驶岬� keyPairGen.initialize(KEY_SIZE, new SecureRandom()); KeyPair keyPair = keyPairGen.genKeyPair(); return keyPair; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 生成公钥 * @param modulus * @param publicExponent * @return RSAPublicKey * @throws Exception */ public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 生成私钥 * @param modulus * @param privateExponent * @return RSAPrivateKey * @throws Exception */ public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent)); try { return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 加密 * @param key 加密的密钥 * @param data 待加密的明文数据 * @return 加密后的数据 * @throws Exception */ public static byte[] encrypt(Key key, byte[] data) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, key); int blockSize = cipher.getBlockSize();//获得加密块大小� i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 解密 * @param key 解密的密钥 * @param raw 已经加密的数据 * @return 解密后的明文 * @throws Exception */ public static byte[] decrypt(Key key, byte[] raw) throws Exception { try { 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 bout.toByteArray(); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("c:/test.html"); FileInputStream in = new FileInputStream(file); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1) { bout.write(tmpbuf, 0, count); tmpbuf = new byte[1024]; } in.close(); byte[] orgData = bout.toByteArray(); KeyPair keyPair = RSA.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate(); byte[] pubModBytes = pubKey.getModulus().toByteArray(); byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray(); byte[] priModBytes = priKey.getModulus().toByteArray(); byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray(); RSAPublicKey recoveryPubKey = RSA.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKey recoveryPriKey = RSA.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[] raw = RSA.encrypt(priKey, orgData); file = new File("c:/encrypt_result.dat"); OutputStream out = new FileOutputStream(file); out.write(raw); out.close(); byte[] data = RSA.decrypt(recoveryPubKey, raw); file = new File("c:/decrypt_result.html"); out = new FileOutputStream(file); out.write(data); out.flush(); out.close(); } } (责任编辑:云子)

java RSA实现对文件加密解密

这个我不清楚。

对文件加密,我使用的是超级加密3000.

超级加密3000采用国际上成熟的加密算法和安全快速的加密方法,可以有效保障数据安全!

具体操作方法:

1下载安装超级加密3000。

2 然后在需要加密的文件上单击鼠标右键选择加密。

3 在弹出的文件加密窗口中设置文件加密密码就OK了。

超级加密3000的下载地址你可以在百度上搜索超级加密3000,第一个就是。

JAVA里面RSA加密算法的使用

RSA的Java实现不能一次加密很大的字符,自己处理了一下,见下面的代码。Base64编码类用的是一个Public domain Base64 for java 其他的保存公钥到文件等简单的实现,就不详细说了,看代码吧。==============================================import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.*;import java.io.*;public class Encryptor {private static final String KEY_FILENAME = "c:\\mykey.dat";private static final String OTHERS_KEY_FILENAME = "c:\\Otherskey.dat";// private static final int KEY_SIZE = 1024;// private static final int BLOCK_SIZE = 117;// private static final int OUTPUT_BLOCK_SIZE = 128;private static final int KEY_SIZE = 2048; //RSA key 是多少位的private static final int BLOCK_SIZE = 245; //一次RSA加密操作所允许的最大长度//这个值与 KEY_SIZE 已经padding方法有关。因为 1024的key的输出是128,2048key输出是256字节//可能11个字节用于保存padding信息了,所以最多可用的就只有245字节了。private static final int OUTPUT_BLOCK_SIZE = 256;private SecureRandom secrand;private Cipher rsaCipher;private KeyPair keys;private MapString, Key allUserKeys;public Encryptor() throws Exception {try {allUserKeys = new HashMapString, Key();secrand = new SecureRandom();//SunJCE Provider 中只支持ECB mode,试了一下只有PKCS1PADDING可以直接还原原始数据,//NOPadding导致解压出来的都是blocksize长度的数据,还要自己处理//参见 另外根据 Open-JDK-6.b17-src( )// 中代码的注释,使用RSA来加密大量数据不是一种标准的用法。所以现有实现一次doFinal调用之进行一个RSA操作,//如果用doFinal来加密超过的一个操作所允许的长度数据将抛出异常。//根据keysize的长度,典型的1024个长度的key和PKCS1PADDING一起使用时//一次doFinal调用只能加密117个byte的数据。(NOPadding 和1024 keysize时128个字节长度)//(2048长度的key和PKCS1PADDING 最多允许245字节一次)//想用来加密大量数据的只能自己用其他办法实现了。可能RSA加密速度比较慢吧,要用AES才行rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();throw e;}ObjectInputStream in;try {in = new ObjectInputStream(new FileInputStream(KEY_FILENAME));} catch (FileNotFoundException e) {if (false == GenerateKeys()){throw e;}LoadKeys();return;}keys = (KeyPair) in.readObject();in.close();LoadKeys();}/** 生成自己的公钥和私钥*/private Boolean GenerateKeys() {try {KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");// secrand = new SecureRandom();// sedSeed之后会造成 生成的密钥都是一样的// secrand.setSeed("chatencrptor".getBytes()); // 初始化随机产生器//key长度至少512长度,不过好像说现在用2048才算比较安全的了keygen.initialize(KEY_SIZE, secrand); // 初始化密钥生成器keys = keygen.generateKeyPair(); // 生成密钥组AddKey("me", EncodeKey(keys.getPublic()));} catch (NoSuchAlgorithmException e) {e.printStackTrace();return false;}ObjectOutputStream out;try {out = new ObjectOutputStream(new FileOutputStream(KEY_FILENAME));} catch (IOException e) {e.printStackTrace();return false;}try {out.writeObject(keys);} catch (IOException e) {e.printStackTrace();return false;} finally {try {out.close();} catch (IOException e) {e.printStackTrace();return false;}}return true;}public String EncryptMessage(String toUser, String Message) throws IOException {Key pubkey = allUserKeys.get(toUser);if ( pubkey == null ){throw new IOException("NoKeyForThisUser") ;}try {//PublicKey pubkey = keys.getPublic();rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey, secrand);//System.out.println(rsaCipher.getBlockSize()); 返回0,非block 加密算法来的?//System.out.println(Message.getBytes("utf-8").length);//byte[] encryptedData = rsaCipher.doFinal(Message.getBytes("utf-8"));byte[] data = Message.getBytes("utf-8");int blocks = data.length / BLOCK_SIZE ;int lastBlockSize = data.length % BLOCK_SIZE ;byte [] encryptedData = new byte[ (lastBlockSize == 0 ? blocks : blocks + 1)* OUTPUT_BLOCK_SIZE];for (int i=0; i blocks; i++){//int thisBlockSize = ( i + 1 ) * BLOCK_SIZE data.length ? data.length - i * BLOCK_SIZE : BLOCK_SIZE ;rsaCipher.doFinal(data,i * BLOCK_SIZE, BLOCK_SIZE, encryptedData ,i * OUTPUT_BLOCK_SIZE);}if (lastBlockSize != 0 ){rsaCipher.doFinal(data, blocks * BLOCK_SIZE, lastBlockSize,encryptedData ,blocks * OUTPUT_BLOCK_SIZE);}//System.out.println(encrypted.length); 如果要机密的数据不足128/256字节,加密后补全成为变为256长度的。//数量比较小时,Base64.GZIP产生的长度更长,没什么优势//System.out.println(Base64.encodeBytes(encrypted,Base64.GZIP).length());//System.out.println(Base64.encodeBytes(encrypted).length());//System.out.println (rsaCipher.getOutputSize(30));//这个getOutputSize 只对 输入小于最大的block时才能得到正确的结果。其实就是补全 数据为128/256 字节return Base64.encodeBytes(encryptedData);} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey") ;}catch (ShortBufferException e) {e.printStackTrace();throw new IOException("ShortBuffer") ;}catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding") ;} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize") ;} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding") ;}finally {//catch 中 return 或者throw之前都会先调用一下这里}}public String DecryptMessage(String Message) throws IOException {byte[] decoded = Base64.decode(Message);PrivateKey prikey = keys.getPrivate();try {rsaCipher.init(Cipher.DECRYPT_MODE, prikey, secrand);int blocks = decoded.length / OUTPUT_BLOCK_SIZE;ByteArrayOutputStream decodedStream = new ByteArrayOutputStream(decoded.length);for (int i =0 ;i blocks ; i ++ ){decodedStream.write (rsaCipher.doFinal(decoded,i * OUTPUT_BLOCK_SIZE, OUTPUT_BLOCK_SIZE));}return new String(decodedStream.toByteArray(), "UTF-8");} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey");} catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding");} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize");} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding");} finally {// catch 中 return 或者throw之前都会先调用一下这里。}}public boolean AddKey(String user, String key) {PublicKey publickey;try {publickey = DecodePublicKey(key);} catch (Exception e) {return false;}allUserKeys.put(user, publickey);SaveKeys();return true;}private boolean LoadKeys() {BufferedReader input;try {input = new BufferedReader(new InputStreamReader(new FileInputStream(OTHERS_KEY_FILENAME)));} catch (FileNotFoundException e1) {// e1.printStackTrace();return false;}

RSA PKCS#1在java中怎么实现?

楼主看看下面的代码是不是你所需要的,这是我原来用的时候收集的

import javax.crypto.Cipher;

import java.security.*;

import java.security.spec.RSAPublicKeySpec;

import java.security.spec.RSAPrivateKeySpec;

import java.security.spec.InvalidKeySpecException;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.io.*;

import java.math.BigInteger;

/**

* RSA 工具类。提供加密,解密,生成密钥对等方法。

* 需要到下载bcprov-jdk14-123.jar。

* RSA加密原理概述

* RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。

* 据猜测,从一个密钥和密文推断出明文的难度等同于分解两个大素数的积

* ===================================================================

* (该算法的安全性未得到理论的证明)

* ===================================================================

* 密钥的产生:

* 1.选择两个大素数 p,q ,计算 n=p*q;

* 2.随机选择加密密钥 e ,要求 e 和 (p-1)*(q-1)互质

* 3.利用 Euclid 算法计算解密密钥 d , 使其满足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互质)

* 4:至此得出公钥为 (n,e) 私钥为 (n,d)

* ===================================================================

* 加解密方法:

* 1.首先将要加密的信息 m(二进制表示) 分成等长的数据块 m1,m2,...,mi 块长 s(尽可能大) ,其中 2^sn

* 2:对应的密文是: ci = mi^e(mod n)

* 3:解密时作如下计算: mi = ci^d(mod n)

* ===================================================================

* RSA速度

* 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论是软件还是硬件实现。

* 速度一直是RSA的缺陷。一般来说只用于少量数据加密。

* 文件名:RSAUtil.javabr

* @author 赵峰br

* 版本:1.0.1br

* 描述:本算法摘自网络,是对RSA算法的实现br

* 创建时间:2009-7-10 下午09:58:16br

* 文件描述:首先生成两个大素数,然后根据Euclid算法生成解密密钥br

*/

public class RSAUtil {

//密钥对

private KeyPair keyPair = null;

/**

* 初始化密钥对

*/

public RSAUtil(){

try {

this.keyPair = this.generateKeyPair();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 生成密钥对

* @return KeyPair

* @throws Exception

*/

private KeyPair generateKeyPair() throws Exception {

try {

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());

//这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低

final int KEY_SIZE = 1024;

keyPairGen.initialize(KEY_SIZE, new SecureRandom());

KeyPair keyPair = keyPairGen.genKeyPair();

return keyPair;

} catch (Exception e) {

throw new Exception(e.getMessage());

}

}

/**

* 生成公钥

* @param modulus

* @param publicExponent

* @return RSAPublicKey

* @throws Exception

*/

private RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {

KeyFactory keyFac = null;

try {

keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

} catch (NoSuchAlgorithmException ex) {

throw new Exception(ex.getMessage());

}

RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));

try {

return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);

} catch (InvalidKeySpecException ex) {

throw new Exception(ex.getMessage());

}

}

/**

* 生成私钥

* @param modulus

* @param privateExponent

* @return RSAPrivateKey

* @throws Exception

*/

private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {

KeyFactory keyFac = null;

try {

keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

} catch (NoSuchAlgorithmException ex) {

throw new Exception(ex.getMessage());

}

RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));

try {

return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);

} catch (InvalidKeySpecException ex) {

throw new Exception(ex.getMessage());

}

}

/**

* 加密

* @param key 加密的密钥

* @param data 待加密的明文数据

* @return 加密后的数据

* @throws Exception

*/

public byte[] encrypt(Key key, byte[] data) throws Exception {

try {

Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

cipher.init(Cipher.ENCRYPT_MODE, key);

// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte;

// 因此共有2个加密块,第一个127 byte第二个为1个byte

int blockSize = cipher.getBlockSize();

// System.out.println("blockSize:"+blockSize);

int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小

// System.out.println("加密块大小:"+outputSize);

int leavedSize = data.length % blockSize;

// System.out.println("leavedSize:"+leavedSize);

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);

// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中

// 而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。

i++;

}

return raw;

} catch (Exception e) {

throw new Exception(e.getMessage());

}

}

/**

* 解密

* @param key 解密的密钥

* @param raw 已经加密的数据

* @return 解密后的明文

* @throws Exception

*/

@SuppressWarnings("static-access")

public byte[] decrypt(Key key, byte[] raw) throws Exception {

try {

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 bout.toByteArray();

} catch (Exception e) {

throw new Exception(e.getMessage());

}

}

/**

* 返回公钥

* @return

* @throws Exception

*/

public RSAPublicKey getRSAPublicKey() throws Exception{

//获取公钥

RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();

//获取公钥系数(字节数组形式)

byte[] pubModBytes = pubKey.getModulus().toByteArray();

//返回公钥公用指数(字节数组形式)

byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();

//生成公钥

RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);

return recoveryPubKey;

}

/**

* 获取私钥

* @return

* @throws Exception

*/

public RSAPrivateKey getRSAPrivateKey() throws Exception{

// 获取私钥

RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

// 返回私钥系数(字节数组形式)

byte[] priModBytes = priKey.getModulus().toByteArray();

// 返回私钥专用指数(字节数组形式)

byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();

// 生成私钥

RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);

return recoveryPriKey;

}

/**

* 测试

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

RSAUtil rsa = new RSAUtil();

String str = "天龙八部、神雕侠侣、射雕英雄传白马啸西风";

RSAPublicKey pubKey = rsa.getRSAPublicKey();

RSAPrivateKey priKey = rsa.getRSAPrivateKey();

// System.out.println("加密后==" + new String(rsa.encrypt(pubKey,str.getBytes())));

String mw = new String(rsa.encrypt(pubKey, str.getBytes()));

System.out.println("加密后:"+mw);

// System.out.println("解密后:");

System.out.println("解密后==" + new String(rsa.decrypt(priKey,rsa.encrypt(pubKey,str.getBytes()))));

}

}

请高手指教如何用java编写RSA算法?谢谢

你是用rsa算法去加密,还是要自己编写一个rsa算法?

RSA是非对称加密算法,可以用它通过KeyPairGenerator来生成KeyPari,它里面有公钥和私钥。

通过Cipher.getInstance("PBEWithMD5AndDES")得到Cipher对象并初始化为加密/解密模式。最doFinal即可完成加解密。除了生成KeyPari外,还可以通过RSA算法的证书和密钥库来得到公/私钥。如果阁下想自己编写一个RSA算法的,本人就无能为力了。

如何用java实现128位密钥的RSA算法

 import javax.crypto.Cipher;

 import sun.misc.BASE64Decoder;

 import sun.misc.BASE64Encoder;

 import java.io.FileInputStream;

 import java.io.FileOutputStream;

 import java.io.ObjectInputStream;

 import java.io.ObjectOutputStream;

 import java.security.Key;

 import java.security.KeyPair;

 import java.security.KeyPairGenerator;

import java.security.SecureRandom;

 public class RSA_Encrypt {

 /** 指定加密算法为DESede */

 private static String ALGORITHM = "RSA";

 /** 指定key的大小 */

 private static int KEYSIZE = 128;

 /** 指定公钥存放文件 */

 private static String PUBLIC_KEY_FILE = "PublicKey";

 /** 指定私钥存放文件 */

 private static String PRIVATE_KEY_FILE = "PrivateKey";

// private static String PUBLIC_KEY_FILE = "D://PublicKey.a";

// private static String PRIVATE_KEY_FILE = "D://PrivateKey.a";

 

 

 /**

 * 生成密钥对

 */

 private static void generateKeyPair() throws Exception{

   /** RSA算法要求有一个可信任的随机数源 */

    SecureRandom sr = new SecureRandom();

    /** 为RSA算法创建一个KeyPairGenerator对象 */

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);

   /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */

    kpg.initialize(KEYSIZE, sr);

    /** 生成密匙对 */

    KeyPair kp = kpg.generateKeyPair();

    /** 得到公钥 */

    Key publicKey = kp.getPublic();

    /** 得到私钥 */

    Key privateKey = kp.getPrivate();

    /** 用对象流将生成的密钥写入文件 */

    ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));

    ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));

    oos1.writeObject(publicKey);

    oos2.writeObject(privateKey);

    /** 清空缓存,关闭文件输出流 */

    oos1.close();

    oos2.close();

 }

 /**

 * 加密方法

 * source: 源数据

 */

 public static String encrypt(String source) throws Exception{

    generateKeyPair();

    /** 将文件中的公钥对象读出 */

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));

    Key key = (Key) ois.readObject();

    ois.close();

    /** 得到Cipher对象来实现对源数据的RSA加密 */

    Cipher cipher = Cipher.getInstance(ALGORITHM);

    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] b = source.getBytes();

    /** 执行加密操作 */

    byte[] b1 = cipher.doFinal(b);

    BASE64Encoder encoder = new BASE64Encoder();

    return encoder.encode(b1);

 }

 /**

 * 解密算法

 * cryptograph:密文

 */

 public static String decrypt(String cryptograph) throws Exception{

    /** 将文件中的私钥对象读出 */

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));

    Key key = (Key) ois.readObject();

    /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */

    Cipher cipher = Cipher.getInstance(ALGORITHM);

    cipher.init(Cipher.DECRYPT_MODE, key);

    BASE64Decoder decoder = new BASE64Decoder();

    byte[] b1 = decoder.decodeBuffer(cryptograph);

    /** 执行解密操作 */

    byte[] b = cipher.doFinal(b1);

    return new String(b);

 }

  

 public static void main(String[] args) {

  try {

   String source = "Hello World!";//要加密的字符串

   String cryptograph = encrypt(source);

   System.out.println(cryptograph);

   

   String target = decrypt(cryptograph);//解密密文

   System.out.println(target);

  } catch (Exception e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }//生成的密文

 }

}