Java RSA加密

来源:互联网 发布:linux write 编辑:程序博客网 时间:2024/06/08 10:31

RSA类:

public class RSA {private Key key = null;private static final String PUBLIC_KEY_FILE = "PublicKey";/** 指定私钥存放文件 */private static final String PRIVATE_KEY_FILE = "PrivateKey";/**加密工具*/private Cipher encryptCipher = null;/** 解密工具 */private Cipher decryptCipher = null;public void createKey() throws NoSuchAlgorithmException,FileNotFoundException, IOException {/** 为RSA算法创建一个KeyPairGenerator对象 */KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */keyPairGen.initialize(1024);/** 生成密匙对 */KeyPair keyPair = keyPairGen.generateKeyPair();/** 得到公钥 */Key publicKey = keyPair.getPublic();/** 得到私钥 */Key privateKey = keyPair.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();}private Key readKey(String keyfilepath) throws Exception, ClassNotFoundException {ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(keyfilepath));    Key key = (Key) objectInputStream.readObject();return key;}public void initialize_encryptkey(String keyfilepath) throws Exception {encryptCipher = Cipher.getInstance("RSA");if(key == null) {key = readKey(keyfilepath);}encryptCipher.init(Cipher.ENCRYPT_MODE, key);key = null;}public byte[] encrypt(byte[] b) throws Exception {return encryptCipher.doFinal(b);}public void initalize_dencryptkey(String keyfilepath) throws Exception {decryptCipher = Cipher.getInstance("RSA");if (key == null) {key = readKey(keyfilepath);}decryptCipher.init(Cipher.DECRYPT_MODE, key);key = null;}public byte[] decrypt(byte[] buf) throws Exception {return decryptCipher.doFinal(buf);}    public void encryptFile(String sourceFileName, String diminationFileName) throws Exception {FileInputStream infile = new FileInputStream(sourceFileName);FileOutputStream outfile = new FileOutputStream(diminationFileName);byte[] b = new byte[117];byte[] newbyte;int a = infile.read(b);while (a != -1) {if(a == b.length) {newbyte = b;} else {newbyte = new byte[a];for(int i = 0; i<a; i++) {newbyte[i] = b[i];}}byte[] ee = encrypt(newbyte);outfile.write(ee);a = infile.read(b);}infile.close();outfile.close();}    public void dencryptFile(String sourceFileName, String diminationFileName) throws Exception {    FileInputStream infile = new FileInputStream(sourceFileName);FileOutputStream outfile = new FileOutputStream(diminationFileName);byte[] b = new byte[128];byte[] newbyte;int a = infile.read(b);while (a != -1) {if(a == b.length) {newbyte = b;} else {newbyte = new byte[a];for(int i = 0; i<a; i++) {newbyte[i] = b[i];}}byte[] ee = decrypt(newbyte);outfile.write(ee);a = infile.read(b);}infile.close();outfile.close();}}