Aes加密算法 Java簡單實現

import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class TestAes {

static final String ALGORITHM="AES";
public static SecretKey generateKey() throws NoSuchAlgorithmException {
    KeyGenerator secretGenerator=KeyGenerator.getInstance(ALGORITHM);//AES 128
    SecureRandom secureRandom=new SecureRandom();//隨機數
    secretGenerator.init(secureRandom);//初始化
    SecretKey secretKey=secretGenerator.generateKey();
    return secretKey;
}
static Charset charset=Charset.forName("UTF-8");
public static byte[] encrypt(String content, SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
return  aes(content.getBytes(charset),Cipher.ENCRYPT_MODE,secretKey);
}

public static String decrypt(byte[] contentArray, SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
byte[] result = aes(contentArray,Cipher.DECRYPT_MODE,secretKey);
return new String(result,"UTF-8");
}

public static byte[] aes(byte[] contentArray,int mode,SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
    Cipher cipher =Cipher.getInstance(ALGORITHM);
    cipher.init(mode,secretKey);
    byte[] result=cipher.doFinal(contentArray);
    return  result;
}

public static void main(String[] args) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException {
    String content="hello world 你好,我是xxx";
    SecretKey secretKey=generateKey();
    byte[] encryptResult=encrypt(content,secretKey);
    System.out.println("加密後的結果爲" +new String(encryptResult,"utf-8"));
    String decryptResult = decrypt(encryptResult,secretKey);
    System.out.println("解密後的結果爲"+decryptResult);
}

}

初中級面試裝逼必備

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