JAVA AES256 ECBwithPKCS7

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

public class AES256ECBwithPKCS7 {

    //add new bouncycastle ciphers
    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    /**
     * encrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {

            byte[] bytes = key.getBytes();
            SecretKeySpec skey = new SecretKeySpec(bytes, "AES");

            byte[] keyBytes = skey.getEncoded();
            String hexKey = ParseSystemUtil.parseByte2HexStr(keyBytes);

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

        return ParseSystemUtil.parseByte2HexStr(crypted);
    }

    /**
     * decrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Hex.decodeHex(input.toCharArray()));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }

}

使用:

public static void main(String[] args) throws Exception {


    String key = "2C4C68B764834D48920A5DE5B2DE3FEC";
    String data = "0123456789";

    String encrypted = AES256ECBwithPKCS7.encrypt(data, key);
    System.out.println("2加密后数据: " +  encrypted);
    String decrypted = AES256ECBwithPKCS7.decrypt(AES256ECBwithPKCS7.encrypt(data, key), key);
    System.out.println("2解密后数据: "  + decrypted);

}

jce_policy里的文件覆盖jre/lib下secrity文件夹的同名文件,比如: jdk1.8.0_112jrelibsecurity。
bcprov 和 codec 引用到项目内。

jce_policy-8.zip
bcprov-jdk15to18-1.69.jar
commons-codec-1.15.jar

JAVAAES256

我来吐槽

*

*