java RSA 簡單加密

package com.security; import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;java

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;算法

/**安全

  • @author Administrator *1976年,美國學者Dime和Henman爲解決信息公開傳送和密鑰管理問題,提出一種新的密鑰交換協議,容許在不安全的媒體上的通信雙方交換信息,安全地達成一致的密鑰, *這就是「公開密鑰系統」。相對於「對稱加密算法」這種方法也叫作「非對稱加密算法」。 與對稱加密算法不一樣,非對稱加密算法須要兩個密鑰:公開密鑰(publickey)和私有密鑰 (privatekey)。公開密鑰與私有密鑰是一對,若是用公開密鑰對數據進行加密,只有用對應的私有密鑰才能解密;若是用私有密鑰對數據進行加密,那麼只有用對應的公開密鑰才能解密。 由於加密和解密使用的是兩個不一樣的密鑰,因此這種算法叫做非對稱加密算法。
  1. RSA 公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。 RSA是目前最有影響力的公鑰加密算法,它可以抵抗到目前爲止已知的全部密碼攻擊,已被ISO推薦爲公鑰數據加密標準。RSA算法基於一個十分簡單的數論事實: 將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,所以能夠將乘積公開做爲加密密鑰。 */ public class RSA {加密

    /**對象

    • 加密 /
      protected byte[] encrypt(RSAPublicKey publicKey,byte[] srcBytes) throws Exception{
      if(publicKey!=null){
      //Cipher負責完成加密或解密工做,基於RSA
      Cipher cipher = Cipher.getInstance("RSA");
      //根據公鑰,對Cipher對象進行初始化
      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      byte[] resultBytes = cipher.doFinal(srcBytes);
      return resultBytes;
      }
      return null;
      }
      /
      *ip

    • 解密
      /
      protected byte[] decrypt(RSAPrivateKey privateKey,byte[] srcBytes) throws Exception{
      if(privateKey!=null){
      //Cipher負責完成加密或解密工做,基於RSA
      Cipher cipher = Cipher.getInstance("RSA");
      //根據公鑰,對Cipher對象進行初始化
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      byte[] resultBytes = cipher.doFinal(srcBytes);
      return resultBytes;
      }
      return null;
      }
      /
      *ci

    • test */
      public static void main(String[] args) throws Exception {
      RSA rsa = new RSA();
      String msg = "張三是好人";
      //KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
      //初始化密鑰對生成器,密鑰大小爲1024位
      keyPairGen.initialize(1024);
      //生成一個密鑰對,保存在keyPair中
      KeyPair keyPair = keyPairGen.generateKeyPair();
      //獲得私鑰
      RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
      //獲得公鑰
      RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();開發

      //用公鑰加密
      byte[] srcBytes = msg.getBytes();
      byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);get

      //用私鑰解密
      byte[] decBytes = rsa.decrypt(privateKey, resultBytes);it

      System.out.println("明文是:" + msg);
      System.out.println("加密後是:" + new String(resultBytes));
      System.out.println("解密後是:" + new String(decBytes));
      }

}

相關文章
相關標籤/搜索