有固定的密钥key的AES加密

package test;

/*****************************************************
 *
 * @author wuzhenzhong
 *
 * @since May 12, 2009
 *
 *****************************************************/
import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class EncryptSample {

 public static void main(String[] args) throws Exception {
  /*
   * 256 bit key
   */
  String key = "aaaaaaaaaabbbbbbaaaaaaaaaabbbbbb";
  /*
   * source data
   */
  System.out.println("source -------- fengye");
  
  String enBytes = EncryptSample.encryptAES("fengye",key);
  
        System.out.println("mi wen --------------- "+enBytes.toString());
       
  String deBytes = EncryptSample.decryptAES(enBytes, key);

  System.out.println("ming wen------------"+new String(deBytes));

 }
 
 /*
  * 转为十六进制
  */
 @SuppressWarnings("unused")
 private static String asHex(byte buf[]) {
  StringBuffer strbuf = new StringBuffer(buf.length * 2);
  int i;

  for (i = 0; i < buf.length; i++) {
   if (((int) buf[i] & 0xff) < 0x10)
    strbuf.append("0");

   strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
  }
  System.out.println(strbuf.toString());
  return strbuf.toString();
 }
 /*
  * 转为二进制
  */
 @SuppressWarnings("unused")
 private static byte[] asBin(String src) {
  if (src.length() < 1)
   return null;
  byte[] encrypted = new byte[src.length() / 2];
  for (int i = 0; i < src.length() / 2; i++) {
   int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
   int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);

   encrypted[i] = (byte) (high * 16 + low);
  }
  return encrypted;
 }
 /*
  * 加密
  */
 public static String encryptAES(String data, String secret_key) {
  byte[] key = asBin(secret_key);
  SecretKeySpec sKey = new SecretKeySpec(key, "AES");
  try {
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.ENCRYPT_MODE, sKey);
   byte[] encrypted = cipher.doFinal(data.getBytes());

   return asHex(encrypted);

  } catch (Exception e) {
   return null;
  }
 }
 /*
  * 解密
  */
 public static String decryptAES(String encData, String secret_key) {
  byte[] tmp = asBin(encData);
  byte[] key = asBin(secret_key);
  SecretKeySpec sKey = new SecretKeySpec(key, "AES");
  try {
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.DECRYPT_MODE, sKey);
   byte[] decrypted = cipher.doFinal(tmp);
   return new String(decrypted);
  } catch (Exception e) {
   return null;
  }
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值