Java AES 256位加密解密

本文介绍了如何在Java中实现AES 256位加密解密,由于Java默认仅支持128位,因此需要引入bouncycastle库以支持PKCS7Padding填充方式。此外,还需下载并安装JCE无限制权限策略文件。通过提供的Base64.java源码和密钥,可以正确解密数据库中256位加密的数据。
摘要由CSDN通过智能技术生成

Java AES解密加密算法默认是支持128位的,但是,最近,做了登录练习,是从数据库里的用户表提取用户账号和密码来进行验证登录,因为用户表里的密码是经过256位加密进行储存的,而且是用PKCS7Padding的填充方式来存储,所以Java默认的128位解密加密读出来的数据与数据库中的数据不匹配,而且Java默认支持的填充方式是PKCS5Padding,所以需要引用第三方jar包bouncycastle组件来让Java里面支持PKCS7Padding填充方式,获取jar包:

链接:https://pan.baidu.com/s/1CguDhW4rVCDh8JrdzsyLlw 

提取码:jj7o

然后还需要下载jce无限制权限策略文件,覆盖到JDK和JRE中,如:

C:\Program Files\Java\jdk1.7.0_80\jre\lib\security

C:\Program Files\Java\jre7\lib\security

根据自己的JAVA_HOME路径

相关文件下载地址:

JDK7:https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

JDK8:http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

然后具体相应代码如下:

先封装一个源码,Base64.java:

import java.io.UnsupportedEncodingException;

public class Base64 {
	   /**
     * Default values for encoder/decoder flags.
     */
    public static final int DEFAULT = 0;
 
    /**
     * Encoder flag bit to omit the padding '=' characters at the end
     * of the output (if any).
     */
    public static final int NO_PADDING = 1;
 
    /**
     * Encoder flag bit to omit all line terminators (i.e., the output
     * will be on one long line).
     */
    public static final int NO_WRAP = 2;
 
    /**
     * Encoder flag bit to indicate lines should be terminated with a
     * CRLF pair instead of just an LF.  Has no effect if {@code
     * NO_WRAP} is specified as well.
     */
    public static final int CRLF = 4;
 
    /**
     * Encoder/decoder flag bit to indicate using the "URL and
     * filename safe" variant of Base64 (see RFC 3548 section 4) where
     * {@code -} and {@code _} are used in place of {@code +} and
     * {@code /}.
     */
    public static final int URL_SAFE = 8;
 
    /**
     * Flag to pass to {@link Base64OutputStream} to indicate that it
     * should not close the output stream it is wrapping when it
     * itself is closed.
     */
    public static final int NO_CLOSE = 16;
 
    //  --------------------------------------------------------
    //  shared code
    //  --------------------------------------------------------
 
    /* package */ static abstract class Coder {
        public byte[] output;
        public int op;
 
        /**
         * Encode/decode another block of input data.  this.output is
         * provided by the caller, and must be big enough to hold all
         * the coded data.  On exit, this.opwill be set to the length
         * of the coded data.
         *
         * @param finish true if this is the final call to process for
         *        this object.  Will finalize the coder state and
         *        include any final bytes in the output.
         *
         * @return true if the input so far is good; false if some
         *         error has been detected in the input stream..
         */
        public abstract boolean process(byte[] input, int offset, int len, boolean finish);
 
        /**
         * @return the maximum number of bytes a call to process()
         * could produce for the given number of input bytes.  This may
         * be an overestimate.
         */
        public abstract int maxOutputSize(int len);
    }
 
    //  --------------------------------------------------------
    //  decoding
    //  --------------------------------------------------------
 
    /**
     * Decode the Base64-encoded data in input and return the data in
     * a new byte array.
     *
     * <p>The padding '=' characters at the end are considered optional, but
     * if any are present, there must be the correct number of them.
     *
     * @param str    the input String to decode, which is converted to
     *               bytes using the default charset
     * @param flags  controls certain features of the decoded output.
     *               Pass {@code DEFAULT} to decode standard Base64.
     *
     * @throws IllegalArgumentException if the input contains
     * incorrect padding
     */
    public static byte[] decode(String str, int flags) {
        return decode(str.getBytes(), flags);
    }
 
    /**
     * Decode the Base64-encoded data in input and return the data in
     * a new byte array.
     *
     * <p>The padding '=' characters at the end are considered optional, but
     * if any are present, there must be the correct number of them.
     *
     * @param input the input array to decode
     * @param flags  controls certain features of the decoded output.
     *               Pass {@code DEFAULT} to decode standard Base64.
     *
     * @throws IllegalArgumentException if the input contains
     * incorrect padding
     */
    public static byte[] decode(byte[] input, int flags) {
        return decode(input, 0, input.length, flags);
    }
 
    /**
     * Decode the Base64-encoded data in input and return the data in
     * a new byte array.
     *
     * <p>The padding '=' characters at the end are considered optional, but
     * if any are present, there must be the correct number of them.
     *
     * @param input  the data to decode
     * @param offset the position within the input array at which to start
     * @param len    the number of bytes of input to decode
     * @param flags  controls certain features of the decoded output.
     *               Pass {@code DEFAULT} to decode standard Base64.
     *
     * @throws IllegalArgumentException if the input contains
     * incorrect padding
     */
    public static byte[] decode(byte[] input, int offset, int len, int flags) {
        // Allocate space for the most data the input could represent.
        // (It could contain less if it contains whitespace, etc.)
        Decoder decoder = new Decoder(flags, new byte[len*3/4]);
 
        if (!decoder.process(input, offset, len, true)) {
            throw new IllegalArgumentException("bad base-64");
        }
 
        // Maybe we got lucky and allocated exactly enough output space.
        if (decoder.op == decoder.output.length) {
            return decoder.output;
        }
 
        // Need to shorten the array, so allocate a new one of the
        // right size and copy.
        byte[] temp = new byte[decoder.op];
        Syste
Java AES256加密解密是一种常用的对称加密算法,它使用256的密钥对数据进行加密和解密。下面是Java中使用AES256进行加密解密的基本步骤: 1. 导入相关的类库: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; ``` 2. 定义加密解密方法: ```java public class AESUtil { private static final String ALGORITHM = "AES"; private static final TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static String encrypt(String data, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 3. 使用加密解密方法: ```java public class Main { public static void main(String[] args) { try { String data = "Hello, World!"; String key = "0123456789abcdef0123456789abcdef"; // 256密钥 String encryptedData = AESUtil.encrypt(data, key); System.out.println("加密后的数据:" + encryptedData); String decryptedData = AESUtil.decrypt(encryptedData, key); System.out.println("解密后的数据:" + decryptedData); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了如何使用Java进行AES256加密解密。需要注意的是,密钥的长度必须是256(32字节),并且在实际应用中应该使用安全的方式来保存和传输密钥。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值