javax.crypto.Cipher 加解密

package com.cslc.pcbp.bet.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;

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

public class AESImpl {

 // 閿熸枻鎷烽敓鏂ゆ嫹AES閿熸枻鎷烽挜
 public static String createKey() {

  try {
   KeyGenerator keygen = KeyGenerator.getInstance("AES");
   SecureRandom random = new SecureRandom();
   keygen.init(random);
   SecretKey key = keygen.generateKey();
   return encodeKey(key);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 public static String encrypt(String key, String message) {
  int mode = Cipher.ENCRYPT_MODE;
  Cipher cipher;
  try {
   cipher = Cipher.getInstance("AES");
   cipher.init(mode, decodeSecretKey(key));
   byte[] data = message.getBytes("UTF-8");
   byte[] encryptedData = crypt(data, cipher);
   return Base64.encodeBase64String(encryptedData);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public static String decrypt(String key, String message) {
  int mode = Cipher.DECRYPT_MODE;
  Cipher cipher;
  try {
   cipher = Cipher.getInstance("AES");
   cipher.init(mode, decodeSecretKey(key));
   byte[] decoded = Base64.decodeBase64(message);
   byte[] decryptedData = crypt(decoded, cipher);
   return new String(decryptedData, "UTF-8");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return null;
 }

 private static byte[] crypt(byte[] bytes, Cipher cipher) throws IOException,
   ShortBufferException, GeneralSecurityException {

  ByteArrayInputStream in = new ByteArrayInputStream(bytes);
  ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length);

  int blockSize = cipher.getBlockSize();
  int outputSize = cipher.getOutputSize(blockSize);

  byte[] inBytes = new byte[blockSize];
  byte[] outBytes = new byte[outputSize];
  int inLength = 0;
  boolean more = true;
  while (more) {
   inLength = in.read(inBytes);
   if (inLength == blockSize) {
    int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
    out.write(outBytes, 0, outLength);
   } else
    more = false;
  }
  if (inLength > 0) {
   outBytes = cipher.doFinal(inBytes, 0, inLength);
  } else {
   outBytes = cipher.doFinal();
  }
  out.write(outBytes);
  return out.toByteArray();
 }

 /**
  * 閿熸枻鎷烽敓鏂ゆ嫹key涓篵ase64閿熻鍑ゆ嫹
  *
  *
  *
  * @return
  */

 private static String encodeKey(Key key) {

  byte[] keyBytes = key.getEncoded();
  String s = Base64.encodeBase64String(keyBytes);

  return s;

 }

 /**
  *
  * 閿熸枻鎷烽敓鏂ゆ嫹base64閿熸枻鎷烽敓鏂ゆ嫹鐜敓鏂ゆ嫹閿熺殕锟�
  *
  *
  *
  * @param key
  *
  *            閿熸枻鎷烽挜閿熻鍑ゆ嫹閿熸枻鎷烽敓鏂ゆ嫹base64閿熸枻鎷烽敓璇級
  *
  * @throws Exception
  */

 private static SecretKeySpec decodeSecretKey(String key) throws Exception {

  byte[] keyBytes;

  keyBytes = Base64.decodeBase64(key);

  //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");

  SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

  //SecretKey privateKey = keyFactory.generateSecret(keySpec);

  return keySpec;

 }

 public static void main(String[] args) {
  String key = "i3MVemr3QxAGmovQuhMjlA==";//AESImpl.createKey();
  System.out.println("key:"+key);
  String encoded = AESImpl.encrypt(key, "{\"code\":0,\"details\":[{\"amount\":1,\"createTime\":\"2013-03-22 00:00:00\",\"type\":1},{\"amount\":1,\"createTime\":\"2013-03-19 00:00:00\",\"type\":1},{\"amount\":1,\"createTime\":\"2013-03-22 00:00:00\",\"type\":1}],\"message\":\"处理正常\"}");
  System.out.println("encoded:"+encoded);
  String decoded = AESImpl.decrypt("i3MVemr3QxAGmovQuhMjlA==", "o7aY7e95TchB9IvqVKRy4yjuUwTFqOe4ttkl1nfEVBupoTtA5AvazNr/4SgbOTjSasGaVOyVV25q himhIRXPp1oiQhmJNahP5vCVAMqUKmlr1ky5skKdEx8LWps7R/TzlDof7V0uZObG6heiFXR8M90D 9RdpVIQC6wYqYs2CQtfekP2/k9GvOqERK5+NTEcw2AfZtdFiQuJ19BLOi91787hoOs8KxKCG7E2w RVBdO0iihwHIUUR68DdEM5lxVrjlLv3b49X8j5iJVbw3qZT4PSTloxEmXGVqfrXzPp9+K9A=");
  System.out.println("decoded:"+decoded);
 
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值