AES加密

来源:互联网 发布:淘宝有卖鳄鱼的吗 编辑:程序博客网 时间:2024/05/16 09:00
import com.sun.crypto.provider.*;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.UnsupportedEncodingException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.Security;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 EncrypAES {//Cipher负责完成加密或解密工作private Cipher c;//该字节数组负责保存加密的结果private byte[] cipherByte;SecretKeySpec skeySpec =null;public EncrypAES() throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException{Security.addProvider(new SunJCE());// convert key to bytesbyte[] keyBytes = "xxxxx".getBytes("UTF-8");// Use the first 16 bytes (or even less if key is shorter)byte[] keyBytes16 = new byte[16];System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));// setup cipherskeySpec = new SecretKeySpec(keyBytes16, "AES");//生成Cipher对象,指定其支持的DES算法c=Cipher.getInstance("AES/CBC/PKCS5Padding");}/** * 对字符串加密 *  * @param str * @return * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidAlgorithmParameterException  */public byte[] Encrytor(String str) throws InvalidKeyException,IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式byte[] iv = new byte[16]; // initialization vector with all 0c.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));// 加密,结果保存进cipherBytecipherByte = c.doFinal(str.getBytes());return cipherByte;}/** * 对字符串解密 *  * @param buff * @return * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidAlgorithmParameterException  */public byte[] Decryptor(byte[] buff) throws InvalidKeyException,IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式byte[] iv = new byte[16]; // initialization vector with all 0c.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv));cipherByte = c.doFinal(buff);return cipherByte;}/** * @param args * @throws NoSuchPaddingException  * @throws NoSuchAlgorithmException  * @throws BadPaddingException  * @throws IllegalBlockSizeException  * @throws InvalidKeyException  */public static void main(String[] args) throws Exception {EncrypAES de1 = new EncrypAES();File file=new File("c:\\d.txt");BufferedReader br=new BufferedReader(new FileReader(new File("c:\\d.txt")));String str;StringBuilder sb=new StringBuilder();while((str=br.readLine())!=null){sb.append(str);}byte[] encontent = de1.Encrytor(sb.toString());String str2=new String(encontent);byte[] en2=str2.getBytes();System.out.println(encontent+"  "+en2);byte[] decontent = de1.Decryptor(encontent);System.out.println("加密后:\n" + new String(encontent));System.out.println("解密后:\n" + new String(decontent));}}



/**     * 用于建立十六进制字符的输出的小写字符数组     */    private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };    /**     * 将字节数组转换为十六进制字符数组     *     * @param data     *            byte[]     * @param toDigits     *            用于控制输出的char[]     * @return 十六进制char[]     */    protected static char[] encodeHex(byte[] data, char[] toDigits) {        int l = data.length;        char[] out = new char[l << 1];        // two characters form the hex value.        for (int i = 0, j = 0; i < l; i++) {            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];            out[j++] = toDigits[0x0F & data[i]];        }        return out;    }

/**     * 将字节数组转换为十六进制字符串     *     * @param data     *            byte[]     * @return 十六进制String     */    public static String encodeHexStr(byte[] data) {        return new String(encodeHex(data, DIGITS_LOWER));    }


/**     * 将十六进制字符转换成一个整数     *     * @param ch     *            十六进制char     * @param index     *            十六进制字符在字符数组中的位置     * @return 一个整数     * @throws RuntimeException     *             当ch不是一个合法的十六进制字符时,抛出运行时异常     */    protected static int toDigit(char ch, int index) {        int digit = Character.digit(ch, 16);        if (digit == -1) {            throw new RuntimeException("Illegal hexadecimal character " + ch                    + " at index " + index);        }        return digit;    }    /**     * 将十六进制字符数组转换为字节数组     *     * @param data     *            十六进制char[]     * @return byte[]     * @throws RuntimeException     *             如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常     */    public static byte[] decodeHex(char[] data) {        int len = data.length;        if ((len & 0x01) != 0) {            throw new RuntimeException("Odd number of characters.");        }        byte[] out = new byte[len >> 1];        // two characters form the hex value.        for (int i = 0, j = 0; j < len; i++) {            int f = toDigit(data[j], j) << 4;            j++;            f = f | toDigit(data[j], j);            j++;            out[i] = (byte) (f & 0xFF);        }        return out;    }


encodeHexStr(encrypt(content.toString()))

new String(decrypt(decodeHex(enStr.toCharArray())));


1 0
原创粉丝点击