首頁  >  文章  >  Java  >  如何實現AES加密?

如何實現AES加密?

PHP中文网
PHP中文网原創
2017-06-20 14:48:081452瀏覽

package util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; ##導入javax.crypto.BadPaddingException;
導入javax.crypto.Cipher;
導入javax.crypto.IllegalBlockSizeException;
導入javax.crypto.KeyGenerator;
#導入javax.crypto.NoSuchdingPadception; ##導入javax.crypto.SecretKey;
導入javax.crypto.spec.SecretKeySpec;
導入org.apache.tomcat.util.codec.binary.Base64;

/**

*

* @author 管理員
*
*/
public class AES {

// 加密

   public static String Encrypt(String sSrc, String sKey) throws Exception {

     if (sKey == null) {##系統。
           System.out.print("Key長度不是16位");
           return null;
       }
       byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
       Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"演算法/模式/補碼方法」## Cipher.ENCRYPT_MODE, skeySpec);
       byte[] 加密= cipher.doFinal(sSrc.getBytes("utf-8"));

return new Base64().encodeToString(entedyp);這裡使用BASE64做轉碼功能,同時可以發揮2次加密的功能。

// 解密
   public static String Decrypt(String sSrc, String sKey) throws Exception {
       try {
     # #                System.out.print("Key為空null");
               return null 為16位元
           if (sKey.length() != 16) {
               System.out.print("Key長度不是16位元");
                [] raw = sKey.getBytes("utf-8");
           SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
           Cipher cipher = Cipher.getInstance("AES/ECB/CS 5, ipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
           try {
             try {
           時         String originalString = new String( original,"utf-8");
               return originalString;
           } catch (Exception e) {##  .
               return null;
}
       } catch (Exception ex) {
           System.out.println(ex.toString());
    # . /**
    * 加密
    *  
    * @param content 需要加密的內容
    * @param password  加密密碼
    * @return
  ##   */  
   public static byte[] encrypt(String content, String password) {  
            = KeyGenerator.getInstance("AES");  
                   kgen.init(128, new SecureRandom (password.getBytes()));  
                   SecretKey secretKey = kgen.generateKey();  
  getd );  
                   SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES") ;  
                   Cipher cipher = Cipher.getInstance("AES");// 建立密碼器 
   gety    ");  
                   cipher.init(Cipher.ENCRYPT_MODE , key);// 初始化 
                   byte[] result = cipher.doFinal(byteContent);       } catch (NoSuchAlgorithmException e) {  
                   e.printStackTrace();
           } catch (NoSuchPaddingException e) {  
                   ##                    e.printStackTrace();  
           } catch (UnsupportedEncodingException e) {  
#                    e.printStackTrace();  
           } catch (IllegalBlockSizeException e) {  
#                   e.printStackTrace();  
           } catch (BadPaddingException e) {  
                   e.printStackTrace();  
           }  
           回復中 null;  
   }  
   /**解密
    * @param content  待解密內容
    * @param password 解密金鑰
    * @return
   */  
   public static byte[]解密(byte[]內容,字串密碼) {  
     KeyGenerator kgen = KeyGenerator.getInstance( "高級加密標準」);  
                    kgen.init(128, new SecureRandom(password.getBytes()));  
                    SecretKey SecretKey = kgen.generateKey();  
                    byte[] enCodeFormat = SecretKey.getEncoded();  
                    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");              
                    Cipher cipher = Cipher.getInstance("AES");//建立密碼器  
          /建立密碼器  
     . ##                    byte[] result = cipher .doFinal(內容);  
                   返回結果; // 加密
           } catch (NoSuchAlgorithmException e) {  
                  e.printStackTrace();  
           } catch (NoSuchPaddingException e) {  
                   e.printStackTrace();  
           } catch (InvalidKeyException e) {  
                   e.printStackTrace();  
           } catch (IllegalBlockSizeException e) {  
                   e.printStackTrace();  
           } catch (BadPaddingException e) {  
                   e.printStackTrace();  
           }  
           回復中 null;  
   }  
   /**將二進位轉換成16進位
    * @param buf
    * @return
   */  
   public static String parseByte2HexStr(byte buf[]) {  
  String 若      
           for (int i = 0; i                  .  
                   if (hex.length() == 1) {  
              
                   }  
                   sb.中上(hex.toUpperCase());  
           }  
           return sb.toString();  
   }  
   /**將16進位轉換為二進位
    * @param hexStr
    * @return
   */  
   public static byte[] parseHexStr2Byte(String hexStr) {  
  1    # 1)               return null;  
           byte[] 結果 = 新 byte[hexStr.length()/2];  
           for (int i = 0;iint high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
                   int low = Integer.parseInt(hexStr. ), 16);  
                   result[i] = (byte) (high * 16 + low);  
   turn
   }  

   public static void main(String [] args) throws Exception {
       /*
        * 此處使用AES-128-ECB加密模式,key需為16位元。
        */
       String cKey = "1234567890123456";
       // 需要加密的字串
System.out.println(cSrc) ;
       // 加密
       String enString = AES.Encrypt(cSrc, cKey);
       System.out.println("加密後的字符串是:" + enystem.out.println("加密後的字符串是:#enystem.out. // 解密
       String DeString = AES.Decrypt(enString, cKey);
       System.out.println("解密後的字串為:" + DeString);

 

       String password = "12345678";  
       //加密 
       System.out.println("加密前:##        System.out.println("加密前:##        S  pt(content, password);  
       String encryptResultStr = parseByte2HexStr(encryptResult);  
       System.out.println("加密後:" + encryptResultStr     byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);  
byte[] decryptResult = decrypt(decryptFrom,password);  
       System.out.println("解密後:" + new String(decryptResult));
   }##}

以上是如何實現AES加密?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn