简单的ASE加密解密功能_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 简单的ASE加密解密功能

简单的ASE加密解密功能

 2012/1/7 16:20:41  gybmike  程序员俱乐部  我要评论(0)
  • 摘要:importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjava.security.Security;/**简单的ASE加密解密功能*/publicclassemisSecurity{privatestaticKeyGeneratorkeygen;privatestaticSecretKeysecretKey;privatestaticCiphercipher
  • 标签:功能 ASE



import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Security;

/*
 *简单的ASE加密解密功能
 */
public class emisSecurity {

  private static KeyGenerator keygen ;
  private static SecretKey secretKey;
  private static Cipher cipher;
  private static emisSecurity security = null;

  private emisSecurity(){

  }

  public static emisSecurity getInstance() throws Exception{
      if(security == null){
        security = new emisSecurity();
        keygen = KeyGenerator.getInstance("AES");
        secretKey = keygen.generateKey();
        cipher =Cipher.getInstance("AES");
      }
    return security;
  }


  //加密
  public String encrypt(String str) throws Exception{
    cipher.init(Cipher.ENCRYPT_MODE,secretKey);

    byte [] src =  str.getBytes();
    byte [] enc = cipher.doFinal(src);

    return parseByte2HexStr(enc);
  }


  //解密
  public String decrypt(String str) throws Exception{
    cipher.init(Cipher.DECRYPT_MODE,secretKey);

    byte[] enc = parseHexStr2Byte(str);
    byte [] dec = cipher.doFinal(enc);

    return new String(dec);
  }

  /**将16进制转换为二进制
   * @param hexStr
   * @return
   */
  public static byte[] parseHexStr2Byte(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
   */
  public static String parseByte2HexStr(byte buf[]) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buf.length; i++) {
      String hex = Integer.toHexString(buf[i] & 0xFF);
      if (hex.length() == 1) {
        hex = '0' + hex;
      }
      sb.append(hex.toUpperCase());
    }
    return sb.toString();
  }






  public static void main(String[] args) throws Exception{

    String str = "select * from users 我";
    String ss =  emisSecurity.getInstance().encrypt(str) ;
    System.out.println(ss);
    System.out.println(emisSecurity.getInstance().decrypt(ss));

  }

}

发表评论
用户名: 匿名