AES加密

筆記:


import org.junit.Test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {

    public static String ALGGORITHM = "AES";

    public static byte[] encory(String content,String password) throws Exception{
       KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
       //用戶密碼作爲隨機數初始化
        kgen.init(128,new SecureRandom(password.getBytes()));
        //得到一個密鑰
        SecretKey secretKey = kgen.generateKey();

        //對密鑰進行基本的編碼
        byte[] encodedFormat = secretKey.getEncoded();
        //轉換成AES專用密鑰
        SecretKeySpec key = new SecretKeySpec(encodedFormat,ALGGORITHM);
        //創建一個密碼器
        Cipher cipher = Cipher.getInstance(ALGGORITHM);

        byte[] byteContent = content.getBytes();
        //開始加密了
        cipher.init(Cipher.ENCRYPT_MODE,key);
        byte[] result = cipher.doFinal(byteContent);
        return result;
    }

    public static byte[] decrypt(byte[] content,String password) throws Exception{
        //創建AES的key生產者
        KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
        //利用用戶密碼最爲隨機數初始化
        kgen.init(128,new SecureRandom(password.getBytes()));
        //根據用戶密碼,生成英特密鑰 (所有對稱算法通用)
        SecretKey secretKeySpec = kgen.generateKey();
        //對密鑰進行基本的編碼
        byte[] enCodeFormat = secretKeySpec.getEncoded();
        //轉換成AES專用的密鑰 RoundKey
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,ALGGORITHM);
        //創建一個密碼器
        Cipher cipher = Cipher.getInstance(ALGGORITHM);

        //解密
        cipher.init(Cipher.DECRYPT_MODE,key);
        byte[] result = cipher.doFinal(content);
        return result;
    }

    @Test
    public void testAES() throws Exception{
        String content = "wwy";
        String password = "123dsad";
        byte[] encory = encory(content,password);
        System.out.println("加密數據: " + new String(encory));

        byte[] decory = decrypt(encory,password);
        System.out.println("解密的數據: " + new String(decory));
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章