java加密算法

package test;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
//加密流程:   明文->二进制密文->十六进制密文->密文
//解密流程:   密文->十六进制密文->二进制密文->明文
         
public class FW {
static Key key;

public static void main(String[] a) {
   String s = "firewall";
   FW.getKey(s);
   System.out.println("密钥:" + s);

   String ming = "我想飞";
   System.out.println("明文:" + ming);

   String strEnc = FW.getEncString(ming);
   System.out.println("密文:" + strEnc);

   System.out.println("明文:" + getDesString(strEnc));
}

// 解密 以String密文输入,String明文输出
public static String getDesString(String min) {
   String ming = null;
   ming = new String(getDesCode(getHex2Byte(min.getBytes())));
   return ming;
}

// 将16进制的密文转换成二进制的密文
public static byte[] getHex2Byte(byte[] b) {
   if ((b.length % 2) != 0)
    throw new IllegalArgumentException("长度不是偶数");
   byte[] b2 = new byte[b.length / 2];
   for (int n = 0; n < b.length; n += 2) {
    String item = new String(b, n, 2);
    // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
    b2[n / 2] = (byte) Integer.parseInt(item, 16);
   }
   return b2;
}

// 将二进制的密文转换成明文
public static String getDesCode(byte[] b) {
   Cipher cipher;
   byte[] byteFina = null;
   try {
    cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byteFina = cipher.doFinal(b);
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    cipher = null;
   }
   return new String(byteFina);
}

// 生成key
public static void getKey(String strKey) {
   try {
    KeyGenerator _generator = KeyGenerator.getInstance("AES");
    _generator.init(new SecureRandom(strKey.getBytes()));
    key = _generator.generateKey();
    _generator = null;
   } catch (Exception e) {
    e.printStackTrace();
   }
}

// 生成密文
public static String getEncString(String s) {
   if (s != null)
    if (s.trim().length() != 0) {
     return getByte2Hex(getByteHex(s.getBytes()));
    }
   return null;
}

// 将加密后的二进制转换成字符串
public static String getByte2Hex(byte[] b) {
   // 转成16进制字符串
   String hs = "";
   String stmp = "";
   for (int n = 0; n < b.length; n++) {
    // 整数转成十六进制表示
    stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
    if (stmp.length() == 1)
     hs = hs + "0" + stmp;
    else
     hs = hs + stmp;
   }
   return hs.toUpperCase(); // 转成大写
}

// 加密byte明文输入,byte[]密文输出
public static byte[] getByteHex(byte[] byteS) {
   byte[] min = null;
   Cipher cipher;
   try {
    cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    min = cipher.doFinal(byteS);
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    cipher = null;
   }
   return min;
}

}

你可能感兴趣的:(java,算法,Security)