1. 程式人生 > >AES加密解密 Java中運用

AES加密解密 Java中運用

upper span pub substring rac ont wid mem log

AES全稱 Advanced Encryption Standard, 高級加密算法,更加安全,可取代DES。

Aes:

技術分享
package com.blog.d201706.encrypt;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;


public class Aes {

    /**
     * 加解密key
     */
    private final Key keySpec;

    /**
     * 構造函數
     * 
@param key */ public Aes(String key){ keySpec = new SecretKeySpec(key.getBytes(), "AES"); } /** * 加密 * @param str * @return */ public String encryt(String str) { // 根據密鑰,對Cipher對象進行初始化,ENCRYPT_MODE表示加密模式 try { Cipher c = Cipher.getInstance("AES"); c.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] src = str.getBytes(); // 加密,結果保存進cipherByte byte[] cipherByte = c.doFinal(src); return parseByte2HexStr(cipherByte); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 解密 * @param deCodeStr *
@return */ public String decrypt(String deCodeStr) { // 根據密鑰,對Cipher對象進行初始化,DECRYPT_MODE表示加密模式 try { if (null == deCodeStr) return null; byte[] buff = parseHexStr2Byte(deCodeStr); Cipher c; c = Cipher.getInstance("AES"); c.init(Cipher.DECRYPT_MODE, keySpec); byte[] cipherByte = c.doFinal(buff); return new String(cipherByte); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 將二進制轉換成16進制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = ‘0‘ + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 將16進制轉換為二進制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } }
View Code

MainAes:

技術分享
package com.blog.d201706.encrypt;


public class MainAes {
    public static void main(String[] args) throws Exception {
        Aes aes = new Aes("1234567890123456");
        String msg = "測試文本:今天周5" + System.currentTimeMillis();
        String encontent = aes.encryt(msg);
        String decontent = aes.decrypt(encontent);
        System.out.println("明文是:" + msg);
        System.out.println("加密後:" + encontent);
        System.out.println("解密後:" + decontent);
    }

}
View Code

AES加密解密 Java中運用