RSA算法加解密(JAVA)

  1. /** 
  2.  * RSA加密算法的演示验证 
  3.  * RSA是一种分组加密算法 
  4.  * 注意:密钥对采用的长度决定了加密块的长度,我这里取的是2048,即256byte 
  5.  * 由于加密块的长度固定为256,因此明文的长度至多为256 - 11 = 245byte 
  6.  * 我这里明文长度取的是128byte,密文长度为256byte,它适合于小文件加密 
  7.  */  
  8. package encrypto;  
  9.   
  10. import java.io.BufferedInputStream;  
  11. import java.io.BufferedOutputStream;  
  12. import java.io.File;  
  13. import java.io.FileInputStream;  
  14. import java.io.FileOutputStream;  
  15. import java.io.IOException;  
  16. import java.io.ObjectInputStream;  
  17. import java.io.ObjectOutputStream;  
  18. import java.security.InvalidKeyException;  
  19. import java.security.Key;  
  20. import java.security.KeyFactory;  
  21. import java.security.KeyPair;  
  22. import java.security.KeyPairGenerator;  
  23. import java.security.NoSuchAlgorithmException;  
  24. import java.security.interfaces.RSAPrivateKey;  
  25. import java.security.interfaces.RSAPublicKey;  
  26. import java.security.spec.InvalidKeySpecException;  
  27. import java.security.spec.PKCS8EncodedKeySpec;  
  28. import java.security.spec.X509EncodedKeySpec;  
  29.   
  30. import javax.crypto.BadPaddingException;  
  31. import javax.crypto.Cipher;  
  32. import javax.crypto.IllegalBlockSizeException;  
  33. import javax.crypto.NoSuchPaddingException;  
  34.   
  35. /** 
  36.  * @author liuhuabai,liuhuabai@163.com 
  37.  * 
  38.  */  
  39. public class RSADemo {  
  40.     /** 
  41.      * 公钥 
  42.      */  
  43.     private RSAPublicKey publicKey;  
  44.     /** 
  45.      * 私钥 
  46.      */  
  47.     private RSAPrivateKey privateKey;  
  48.     /** 
  49.      * 用于加解密 
  50.      */  
  51.     private Cipher cipher;  
  52.     /** 
  53.      * 明文块的长度 它必须小于密文块的长度 - 11 
  54.      */  
  55.     private int originLength = 128;  
  56.     /** 
  57.      * 密文块的长度 
  58.      */  
  59.     private int encrytLength = 256;  
  60.       
  61.     /** 
  62.      * 得到初始化的公钥和私钥 
  63.      * @throws NoSuchAlgorithmException  
  64.      * @throws NoSuchPaddingException  
  65.      */  
  66.     public void initKey() throws NoSuchAlgorithmException, NoSuchPaddingException {  
  67.         //RSA加密算法:创建密钥对,长度采用2048  
  68.         KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");  
  69.         kg.initialize(encrytLength * 8);  
  70.         KeyPair keypair = kg.generateKeyPair();  
  71.         //分别得到公钥和私钥  
  72.         publicKey = (RSAPublicKey) keypair.getPublic();  
  73.         privateKey = (RSAPrivateKey) keypair.getPrivate();  
  74.     }  
  75.     /** 
  76.      * 将公钥保存至文件 
  77.      * @param file 待写入的文件 
  78.      * @return true 写入成功;false 写入失败 
  79.      */  
  80.     public boolean savePublicKey(File file) {  
  81.         return this.saveKey(publicKey, file);  
  82.     }  
  83.     /** 
  84.      * 将私钥保持至文件 
  85.      * @param file 待写入的文件 
  86.      * @return true 写入成功;false 写入失败 
  87.      */  
  88.     public boolean savePrivateKey(File file) {  
  89.         return this.saveKey(privateKey, file);  
  90.     }  
  91.     //将Key文件保持到文件中  
  92.     private boolean saveKey(Key key,File file) {  
  93.         boolean write;  
  94.         FileOutputStream fos = null;  
  95.         try {  
  96.             fos = new FileOutputStream(file);  
  97.             ObjectOutputStream oos = new ObjectOutputStream(fos);  
  98.             //System.out.println(key.getFormat());  
  99.             //公钥默认使用的是X.509编码,私钥默认采用的是PKCS #8编码  
  100.             byte [] encode = key.getEncoded();  
  101.             //注意,此处采用writeObject方法,读取时也要采用readObject方法  
  102.             oos.writeObject(encode);  
  103.             write = true;  
  104.         } catch (IOException e) {  
  105.             write = false;  
  106.         } finally {  
  107.                 try {  
  108.                     if(fos != null) fos.close();  
  109.                 } catch (IOException e) {  
  110.                     e.printStackTrace();  
  111.                 }  
  112.         }  
  113.         return write;  
  114.     }  
  115.     /** 
  116.      * 从文件中得到公钥 
  117.      * @param file 保存公钥的文件 
  118.      */  
  119.     public void getPublicKey(File file) {  
  120.         getKey(file,0);  
  121.     }  
  122.     /** 
  123.      * 从文件中得到私钥 
  124.      * @param file 保存私钥的文件 
  125.      */  
  126.     public void getPrivateKey(File file) {  
  127.         getKey(file,1);  
  128.     }  
  129.       
  130.     private void getKey(File file,int mode) {  
  131.         FileInputStream fis;  
  132.         try {  
  133.             //读取数据  
  134.             fis = new FileInputStream(file);  
  135.             ObjectInputStream ois = new ObjectInputStream(fis);  
  136.             byte [] keybyte = (byte[]) ois.readObject();  
  137.             //关闭资源  
  138.             ois.close();  
  139.             //默认编码  
  140.             KeyFactory keyfactory = KeyFactory.getInstance("RSA");  
  141.             //得到公钥或是私钥  
  142.             if(mode == 0) {  
  143.                 X509EncodedKeySpec x509eks= new X509EncodedKeySpec(keybyte);  
  144.                 publicKey = (RSAPublicKey) keyfactory.generatePublic(x509eks);  
  145.                 //System.out.println(pk.getAlgorithm());  
  146.             } else {  
  147.                 PKCS8EncodedKeySpec pkcs8eks = new PKCS8EncodedKeySpec(keybyte);  
  148.                 privateKey = (RSAPrivateKey) keyfactory.generatePrivate(pkcs8eks);  
  149.                 //System.out.println(pk.getAlgorithm());  
  150.             }  
  151.         } catch (IOException e) {  
  152.             e.printStackTrace();  
  153.         } catch (NoSuchAlgorithmException e) {  
  154.             e.printStackTrace();  
  155.         } catch (InvalidKeySpecException e) {  
  156.             e.printStackTrace();  
  157.         } catch (ClassNotFoundException e) {  
  158.             e.printStackTrace();  
  159.         }         
  160.     }  
  161.   
  162.     /** 
  163.      * 数据RSA加密 
  164.      * @param origin 明文 
  165.      * @return 密文 
  166.      */  
  167.     protected byte [] encrypt(byte [] origin) {  
  168.         //byte [] enc = new byte [encrytLength];  
  169.         byte [] enc = null;  
  170.         try {  
  171.             cipher = Cipher.getInstance("RSA");  
  172.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  173.             enc = cipher.doFinal(origin);  
  174.         } catch (NoSuchAlgorithmException e) {  
  175.             e.printStackTrace();  
  176.         } catch (NoSuchPaddingException e) {  
  177.             e.printStackTrace();  
  178.         } catch (InvalidKeyException e) {  
  179.             e.printStackTrace();  
  180.         } catch (IllegalBlockSizeException e) {  
  181.             e.printStackTrace();  
  182.         } catch (BadPaddingException e) {  
  183.             e.printStackTrace();  
  184.         }  
  185.         return enc;  
  186.     }  
  187.     /** 
  188.      * 数据RSA解密 
  189.      * @param enc 密文 
  190.      * @return 明文 
  191.      */  
  192.     protected byte [] decrypt(byte [] enc) {  
  193.         //byte [] origin = new byte [originLength];  
  194.         byte [] origin = null;  
  195.         try {  
  196.             cipher = Cipher.getInstance("RSA");  
  197.             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  198.             origin = cipher.doFinal(enc);  
  199.         } catch (NoSuchAlgorithmException e) {  
  200.             e.printStackTrace();  
  201.         } catch (NoSuchPaddingException e) {  
  202.             e.printStackTrace();  
  203.         } catch (InvalidKeyException e) {  
  204.             e.printStackTrace();  
  205.         } catch (IllegalBlockSizeException e) {  
  206.             e.printStackTrace();  
  207.         } catch (BadPaddingException e) {  
  208.             e.printStackTrace();  
  209.         }  
  210.         return origin;  
  211.     }  
  212.     /** 
  213.      * 加密文件 
  214.      * @param origin 明文件 
  215.      * @throws IOException 
  216.      */  
  217.     public void encryptFile(File origin) throws IOException {  
  218.         FileInputStream fis = null;  
  219.         FileOutputStream fos = null;  
  220.           
  221.         //读入  
  222.         fis = new FileInputStream(origin);  
  223.         BufferedInputStream bis = new BufferedInputStream(fis);  
  224.         byte [] originbyte = new byte [originLength];  
  225.         //写出  
  226.         fos = new FileOutputStream(new File(origin+".encrypt"));  
  227.         BufferedOutputStream bos = new BufferedOutputStream(fos);  
  228.         byte [] encryptbyte;  
  229.         //int k;  
  230.         while(bis.read(originbyte) > 0) {  
  231.             encryptbyte = this.encrypt(originbyte);  
  232.             bos.write(encryptbyte);  
  233.             originbyte = new byte[originLength];  
  234.         }  
  235.         //压入  
  236.         bos.flush();  
  237.         //关闭资源  
  238.         if(fis != null) fis.close();  
  239.         if(fos != null) fos.close();          
  240.     }  
  241.     /** 
  242.      * 解密文件 
  243.      * @param encrypt 密文件 
  244.      * @throws IOException 
  245.      */  
  246.     public void decryptFile(File encrypt) throws IOException {  
  247.           
  248.         FileInputStream fis = null;  
  249.         FileOutputStream fos = null;  
  250.         //读入  
  251.         fis = new FileInputStream(encrypt);  
  252.         BufferedInputStream bis = new BufferedInputStream(fis);  
  253.         byte [] encryptbyte = new byte [encrytLength];  
  254.         //写出  
  255.         fos = new FileOutputStream(new File(encrypt+".decrypt"));  
  256.         BufferedOutputStream bos = new BufferedOutputStream(fos);  
  257.         byte [] originbyte;  
  258.           
  259.         //int k;  
  260.         while(bis.read(encryptbyte) > 0) {  
  261.             originbyte = this.decrypt(encryptbyte);  
  262.             bos.write(originbyte);  
  263.             encryptbyte = new byte [encrytLength];  
  264.         }  
  265.         //压入  
  266.         bos.flush();  
  267.         //关闭资源  
  268.         if(fis != null) fis.close();  
  269.         if(fos != null) fos.close();  
  270.     }  
  271.       
  272.     /** 
  273.      * @param args 
  274.      * @throws IOException  
  275.      */  
  276.     public static void main(String[] args) throws Exception {  
  277.         RSADemo rsa = new RSADemo();  
  278.         rsa.initKey();  
  279.         rsa.encryptFile(new File("E:/hello.txt"));  
  280.         rsa.decryptFile(new File("E:/hello.txt.encrypt"));  
  281.         rsa.savePublicKey(new File("E:/public.key"));  
  282.         rsa.savePrivateKey(new File("E:/private.key"));  
  283.         //rsa.getPublicKey(new File("E:/public.key"));  
  284.         //rsa.getPrivateKey(new File("E:/private.key"));  
  285.         //rsa.encryptFile(new File("E:/hello.txt"));  
  286.         //rsa.decryptFile(new File("E:/hello.txt.encrypt"));  
  287.     }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值