JAVA中使用AES加密


/*待加密的数据*/
byte[] data = "ABCDEFGHIJKLMNOP".getBytes(Charset.defaultCharset());
/*用来存储加密后的数据*/
byte[] encryptDate = new byte[data.length];
/*密钥*/
byte[] key = "1234567890123456".getBytes(Charset.defaultCharset());
/*初始向量IV*/
byte[] iv = "1234567890123456".getBytes(Charset.defaultCharset());

1.首先是创建一个加密器Cipher:

Cipher encoder = Cipher.getInstance("AES/CBC/NoPadding");

2.创建一个SecretKeySpec密钥对象:

SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

3.创建初始向量IV(CBC模式):

IvParameterSpec ivParam = new IvParameterSpec(iv);

4.初始化加密器:

encoder.init(Cipher.ENCRYPT_MODE, keySpec, ivParam);

5.执行加密:

encryptData = encoder.doFinal(data);

完整代码:

import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        byte[] data = "ABCDEFGHIJKLMNOP".getBytes(Charset.defaultCharset());
        byte[] encryptData = new byte[data.length];
        byte[] key = "1234567890123456".getBytes(Charset.defaultCharset());
        byte[] iv = "1234567890123456".getBytes(Charset.defaultCharset());
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParam = new IvParameterSpec(iv);
        try{
            Cipher encoder = Cipher.getInstance("AES/CBC/NoPadding");
            encoder.init(Cipher.ENCRYPT_MODE,keySpec,ivParam);
            encryptData = encoder.doFinal(data);
        }catch(NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e){
            /*do something*/
        } 
    }
}

你可能感兴趣的:(JAVA)