JAVA 的 AES 加密方式使用

简单的AES加密,废话不多说,直接代码

=============================

package cn.enc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
 *
 * %Encrtry%。
 * <p>%类的简介%。</p>
 *
 * @author arron.huang
 * @version v1.0.0
 * <p><B>last update </B> by arron.huang @ 2011-9-7</p>
 * @since v1.0.0
 */
public class Encrtry {

 /**
  * 加密参数
  */
 public final static int enc = Cipher.ENCRYPT_MODE;
 /**
  * 解密码参数
  */
 public final static int dec = Cipher.DECRYPT_MODE;
 
 public static void main(String[] args) throws Exception{

  String message = "欢迎来到我的AES加密基地";
  String fileName = "aaa.dat";
  
  System.out.println("需要机密数据>>>>>>>>>" + message);
  
  String enc_String = sign(message, fileName,  enc);
  System.out.println("加密后可以显示数据>>>>>"+enc_String+"<<<<<");
  System.out.println("机密后长度>>>>>>>>>>>>>" + enc_String.length() + "<<<<<<<<<<<<<<<<");
  
  String dec_String = sign(enc_String, fileName, dec);
  
  System.out.println("解密后数据>>>>" + dec_String + "<<<<<<<<");
  
 }
 
 /**
  *
  * %加密message 返回加密后数据(注:句号不能删除,本注应删除)%。
  * <p>%传入message 返回message机密后数据,使用AES加密方式,(简单方法可不必详述)%。</p>
  * @param message  需要加密或者解密数据字符串
  * @param encType
  * @return String 根据不同encType 加密解密,返回可能是加密后数据,或者解密后数据
  */
 public static String sign(String message, String file, int encType) {
  String sign = "";
  Key key = null;
  if(null == message || "".equals(message)) {
   return sign;
  }
  try {
   FileInputStream inputStream = new FileInputStream("encrtry.k8");
   ObjectInputStream ois = new ObjectInputStream(inputStream);
   key = (Key) ois.readObject();
   ois.close();
   inputStream.close();
  } catch (FileNotFoundException e) {
   System.out.println("加密文件未找到");
  } catch (IOException e) {
   e.printStackTrace();
   System.out.println("流读取出错");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
   System.out.println("类转换错误,读取Key文件错误");
  }
  
   try {
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(encType, key);
   switch (encType) {
   case Cipher.ENCRYPT_MODE:
    byte [] bytes = cipher.doFinal(message.getBytes());
    sign = outputStream(bytes, file);
    break;
   case Cipher.DECRYPT_MODE:
    byte [] bys = inputStream(file);
    sign = new String(cipher.doFinal(bys));
    break;
   default:
    break;
   }
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchPaddingException e) {
   e.printStackTrace();
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  }
   return sign;
 }
 
 /**
  *
  * %字节数据保存到临时文件中(注:句号不能删除,本注应删除)%。
  * <p>%方法详述(简单方法可不必详述)%。</p>
  * @param bytes 读取字符
  * @param file 临时保存文件路径包括文件名
  * @return
  */
 private static String outputStream(byte [] bytes, String file) {
  try {
   FileOutputStream outputStream = new FileOutputStream(file);
   outputStream.write(bytes);
   outputStream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return parseBytes2Hex(bytes);
 }
 
 private static byte [] inputStream(String file) {
  byte [] sr = null;
  try {
   FileInputStream inputStream = new FileInputStream(file);
   sr = new byte [inputStream.available()];
   int totle = 0;
   int len = inputStream.read(sr);
   while(len > 0) {
    totle += len;
    len = inputStream.read(sr, totle, sr.length - totle);
   }
   inputStream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return sr;
 }
 
 /**
  *
  * %产生唯一钥匙(注:句号不能删除,本注应删除)%。
  * <p>%通过AES方式产生一把以后需要使用的钥匙,只需要调用一次(简单方法可不必详述)%。</p>
  *
  * @param String file 文件地址
  *
  */
 private static void encrtry(String fila) {
  try {
   Cipher cipher = Cipher.getInstance("AES");
   SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();

   FileOutputStream fileOutput = new FileOutputStream("encrtry.k8");
   ObjectOutputStream obj = new ObjectOutputStream(fileOutput);
   
   obj.writeObject(secretKey);
   
   obj.close();
   fileOutput.close();
   
   cipher.init(Cipher.ENCRYPT_MODE, secretKey);
   byte [] bytes = cipher.doFinal("12324".getBytes());
   System.out.println(new String(bytes));
   
   cipher.init(Cipher.DECRYPT_MODE, secretKey);
   System.out.println(new String(cipher.doFinal(bytes)));
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    private static byte[] parseHex2Bytes(String hexStr) {
            if (hexStr.length() < 1)
                    return null;
            byte[] result = new byte[hexStr.length()/2];
            for (int i = 0;i< hexStr.length()/2; i++) {
                    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                    result[i] = (byte) (high * 16 + low);
            }
            return result;
    }
 
   
    /**
     * 将二进制转换成16进制
     * @param buf
     * @return
     */
    private static String parseBytes2Hex(byte bys[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bys.length; i++) {
                    String hex = Integer.toHexString(bys[i] & 0xFF);
                    if (hex.length() == 1) {
                            hex = '0' + hex;
                    }
                    sb.append(hex.toUpperCase());
            }
            return sb.toString();
    }
   
}

 

====================测试输出结果=================

需要机密数据>>>>>>>>>欢迎来到我的AES加密基地
加密后可以显示数据>>>>>3C48399D64D3388D0348262ECC45AE27BFB010FF77712088FE05A92A7282477B<<<<<
加密后长度>>>>>>>>>>>>>64<<<<<<<<<<<<<<<<
解密后数据>>>>欢迎来到我的AES加密基地<<<<<<<<

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值