RSA加密解密-实例

package com.service;

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.Key; import java.security.KeyFactory; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Map;

import javax.crypto.Cipher;

import org.apache.axiom.util.base64.Base64Utils;

/**  * 类名: RSAService  * 描述:  * @author admin  * @date 2013-2-20 下午1:31:16  *  *  */ public class RSAService {  private static final String SPLIT_STRING="--";  public static void main(String[] args) {   try { //   SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //   System.out.println(sdf.format(new Date())); //   encryptFile("D:\\test\\admin.rar","D:\\test\\admin0.rar"); //   decryptFile("D:\\test\\admin0.rar","D:\\test\\admin1.rar"); //   System.out.println(sdf.format(new Date()));    /*********运行命令执行*********/    System.out.println("参数个数:"+args.length);    if(args.length==3){             if(args[0].equals("e")){      System.out.println("操作类型:加密");     }else if(args[0].equals("d")){      System.out.println("操作类型:解密");     }     System.out.println("源文件路径:"+args[1]);     System.out.println("目标文件路径:"+args[2]);           if(args[0].equals("e")){      encryptFile(args[1],args[2]);     }else if(args[0].equals("d")){      decryptFile(args[1],args[2]);     }else{      System.out.println("标识符错误,e表示加密,d表示解密");     }    }else{     System.out.println("第一个参数:e表示加密,d表示解密");     System.out.println("第二个参数:源文件路径,如:c:\\src.txt");     System.out.println("第三个参数:目标文件路径,如:c:\\dest.txt");    }   } catch (Exception e) {    System.out.println("第一个参数:e表示加密,d表示解密");    System.out.println("第二个参数:源文件路径,如:c:\\src.txt");    System.out.println("第三个参数:目标文件路径,如:c:\\dest.txt");    e.printStackTrace();   }  }    /**   *   * 方法描述:   * @param srcFileName 要加密的文件   * @param destFileName 加密后存放的文件名   * @throws Exception   * void   * @author admin   * @date 2013-2-20 下午2:52:29   */  public static boolean encryptFile(String srcFileName,

            String destFileName) throws Exception {

      OutputStream outputWriter = null;

      InputStream inputReader = null;       boolean bool=true;       try {         Map<String, Object> keyMap = RSAUtils.genKeyPair();         String  publicKey = RSAUtils.getPublicKey(keyMap);         String  privateKey = RSAUtils.getPrivateKey(keyMap);           byte[] srcfilebyte=fileToByte(srcFileName);           byte[] tep=RSAUtils.encryptByPublicKey(srcfilebyte,publicKey);           OutputStreamWriter os = new OutputStreamWriter( new FileOutputStream(destFileName));       os.write(privateKey+SPLIT_STRING+Base64Utils.encode(tep));                                                                      os.close();       } catch (Exception e) {         bool=false;             throw e;       } finally {             try {                 if (outputWriter != null) {                     outputWriter.close();                 }                 if (inputReader != null) {                     inputReader.close();                 }             } catch (Exception e) {              e.printStackTrace();             }

      }       return bool;   }  /**   *   * 方法描述: 解密   * @param srcFileName 要解密的文件   * @param destFileName 解密后存放的文件名   * @throws Exception   * void   * @author admin   * @date 2013-2-20 下午2:51:18   */  public static boolean decryptFile(String srcFileName,

            String destFileName) throws Exception {

      OutputStream outputWriter = null;

      InputStream inputReader = null;       boolean bool=true;       try {

         Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",                  new org.bouncycastle.jce.provider.BouncyCastleProvider());          FileInputStream in = new FileInputStream(srcFileName);           byte[] data_ = new byte[0];             ByteArrayOutputStream out_ = new ByteArrayOutputStream(2048);             byte[] cache1_ = new byte[1024];             int nRead_ = 0;             while ((nRead_ = in.read(cache1_)) != -1) {                 out_.write(cache1_, 0, nRead_);                 out_.flush();             }             out_.close();             in.close();             data_ = out_.toByteArray(); //            System.out.println(new String(data_));             String result=new String(data_);             String[] strKey=result.split(SPLIT_STRING);           byte[] content=Base64Utils.decode(strKey[1]);//内容             byte[] keyBytes = Base64Utils.decode(strKey[0]);//密钥-私钥             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);             KeyFactory keyFactory = KeyFactory.getInstance("RSA");             Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);                         cipher.init(Cipher.DECRYPT_MODE, privateK);                         outputWriter = new FileOutputStream(destFileName);

            inputReader = new FileInputStream(srcFileName);

            int inputLen = content.length;             ByteArrayOutputStream out = new ByteArrayOutputStream();             int offSet = 0;             byte[] cache;             int i = 0;             // 对数据分段解密             while (inputLen - offSet > 0) {                 if (inputLen - offSet > 128) {                     cache = cipher.doFinal(content, offSet, 128);                 } else {                     cache = cipher.doFinal(content, offSet, inputLen - offSet);                 }                 out.write(cache, 0, cache.length);                 i++;                 offSet = i * 128;             }             byte[] decryptedData = out.toByteArray();             out.close();             outputWriter.write(decryptedData);             outputWriter.flush();             outputWriter.close();

      } catch (Exception e) {        bool=true;             throw e;

      } finally {

            try {

                if (outputWriter != null) {

                    outputWriter.close();

                }

                if (inputReader != null) {

                    inputReader.close();

                }

            } catch (Exception e) {

            }

      }       return bool;   }  /**   *   * 方法描述: 转化为字节   * @param filePath 文件路径   * @return   * @throws Exception   * byte[]   * @author admin   * @date 2013-2-26 下午5:30:28   */  public static byte[] fileToByte(String filePath) throws Exception {         byte[] data = new byte[0];         File file = new File(filePath);         if (file.exists()) {             FileInputStream in = new FileInputStream(file);             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);             byte[] cache = new byte[1024];             int nRead = 0;             while ((nRead = in.read(cache)) != -1) {                 out.write(cache, 0, nRead);                 out.flush();             }             out.close();             in.close();             data = out.toByteArray();          }         return data;     } }

 

package com.service;

import java.io.ByteArrayOutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map;

import javax.crypto.Cipher;

import org.apache.axiom.util.base64.Base64Utils;

/**  * 类名: RSAUtils  * 描述:  * @author admin  * @date 2013-2-19 下午4:15:20  *  *  */ public class RSAUtils {

    /** *//**      * 加密算法RSA      */     public static final String KEY_ALGORITHM = "RSA";         /** *//**      * 签名算法      */     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /** *//**      * 获取公钥的key      */     private static final String PUBLIC_KEY = "RSAPublicKey";         /** *//**      * 获取私钥的key      */     private static final String PRIVATE_KEY = "RSAPrivateKey";         /** *//**      * RSA最大加密明文大小      */     private static final int MAX_ENCRYPT_BLOCK = 117;         /** *//**      * RSA最大解密密文大小      */     private static final int MAX_DECRYPT_BLOCK = 128;

    /** *//**      * <p>      * 生成密钥对(公钥和私钥)      * </p>      *      * @return      * @throws Exception      */     public static Map<String, Object> genKeyPair() throws Exception {         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);         keyPairGen.initialize(1024);         KeyPair keyPair = keyPairGen.generateKeyPair();         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();         Map<String, Object> keyMap = new HashMap<String, Object>(2);         keyMap.put(PUBLIC_KEY, publicKey);         keyMap.put(PRIVATE_KEY, privateKey);         return keyMap;     }

    /** *//**      * <P>      * 私钥解密      * </p>      *      * @param encryptedData 已加密数据      * @param privateKey 私钥(BASE64编码)      * @return      * @throws Exception      */     public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)             throws Exception {         byte[] keyBytes = Base64Utils.decode(privateKey);         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());         cipher.init(Cipher.DECRYPT_MODE, privateK);         int inputLen = encryptedData.length;         ByteArrayOutputStream out = new ByteArrayOutputStream();         int offSet = 0;         byte[] cache;         int i = 0;         // 对数据分段解密         while (inputLen - offSet > 0) {             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);             } else {                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);             }             out.write(cache, 0, cache.length);             i++;             offSet = i * MAX_DECRYPT_BLOCK;         }         byte[] decryptedData = out.toByteArray();         out.close();         return decryptedData;     }

    /** *//**      * <p>      * 公钥加密      * </p>      *      * @param data 源数据      * @param publicKey 公钥(BASE64编码)      * @return      * @throws Exception      */     public static byte[] encryptByPublicKey(byte[] data, String publicKey)             throws Exception {         byte[] keyBytes = Base64Utils.decode(publicKey);         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);         Key publicK = keyFactory.generatePublic(x509KeySpec);         // 对数据加密         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());         cipher.init(Cipher.ENCRYPT_MODE, publicK);         int inputLen = data.length;         ByteArrayOutputStream out = new ByteArrayOutputStream();         int offSet = 0;         byte[] cache;         int i = 0;         // 对数据分段加密         while (inputLen - offSet > 0) {             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);             } else {                 cache = cipher.doFinal(data, offSet, inputLen - offSet);             }             out.write(cache, 0, cache.length);             i++;             offSet = i * MAX_ENCRYPT_BLOCK;         }         byte[] encryptedData = out.toByteArray();         out.close();         return encryptedData;     }

    /** *//**      * <p>      * 获取私钥      * </p>      *      * @param keyMap 密钥对      * @return      * @throws Exception      */     public static String getPrivateKey(Map<String, Object> keyMap)             throws Exception {         Key key = (Key) keyMap.get(PRIVATE_KEY);         return Base64Utils.encode(key.getEncoded());     }

    /** *//**      * <p>      * 获取公钥      * </p>      *      * @param keyMap 密钥对      * @return      * @throws Exception      */     public static String getPublicKey(Map<String, Object> keyMap)             throws Exception {         Key key = (Key) keyMap.get(PUBLIC_KEY);         return Base64Utils.encode(key.getEncoded());     }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值