AES加密

作者: ShrJanLan | 来源:发表于2021-10-22 10:28 被阅读0次
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    /**
     * key generation
     * @return
     * @throws Exception
     */
    public static byte[] key() throws Exception{
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        //低版本JDK,使用密钥长度128位或192位
        keyGen.init(256);
        SecretKey secretKey = keyGen.generateKey();
        return secretKey.getEncoded();
    }

    public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static String hex(byte[] in) {
        StringBuilder sb = new StringBuilder();
        for (byte b : in) {
            sb.append(String.format("%02x", b&0xff));
        }
        return sb.toString();
    }

    public static byte[] byteArray(String hex) {
        byte[] in = new byte[hex.length()/2];
        for(int i = 0; i < in.length; i++) {
            in[i] = (byte) (0xff & Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16));
        }
        return in;
    }

}

加密文件名及解密

try {
    byte[] key = AESUtil.key();
    byte[] encrypt = AESUtil.encrypt("文件名".getBytes(), key);
    String hex = AESUtil.hex(encrypt);
    System.out.println(hex);
    byte[] decrypt = AESUtil.decrypt(AESUtil.byteArray(hex), key);
    System.out.println(new String(decrypt));
} catch (Exception e) {
    e.printStackTrace();
}

相关文章

网友评论

      本文标题:AES加密

      本文链接:https://www.haomeiwen.com/subject/lvucaltx.html