AES加密

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 bytes
		byte[] 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 cipher
		skeySpec = 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 0
		c.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
		// 加密,结果保存进cipherByte
		cipherByte = 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 0
		c.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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值