AES的加密和解密案例

来源:互联网 发布:视频文件旋转角度软件 编辑:程序博客网 时间:2024/05/21 22:26
public class MyAESUtil {


/**
* 加密�?6进制编码方式
* @param input 待加密内�?
* @param key 加密密钥
* @return
*/
public static String encryptHex(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
} catch (Exception e) {
System.out.println(e.toString());
}

StringBuffer sHex = new StringBuffer();
// 把密文转换成十六进制的字符串形式
for (int i = 0; i < crypted.length; i++) {
String s = Integer.toHexString(0xFF & crypted[i]);
if (s.length() == 1)
s = "0" + s;


sHex.append(s);
}


return new String(sHex);
}


/**
* 解密�?6进制编码方式
* @param input 待解密内�?
* @param key 解密密钥
* @return
*/
public static String decryptHex(String input, String key) {
String result = "";
byte[] output = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);

output = new byte[input.length() / 2];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) (0xff & Integer.parseInt(
input.substring(i * 2, i * 2 + 2), 16));
}

output = cipher.doFinal(output);
result = new String(output);
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
public static void main(String[] args) {
String input="03501080220150052813";
String key="TAIPING@EZT_1108";
String enc = encryptHex(input, key);
System.out.println("加密之后:" + enc);
String dec = decryptHex(enc, key);
System.out.println("解密之后:" + dec);
}

}



结果:

加密之后:418e2c6b3e936d40b2b8fd9750d667367eaeb77f7bea7485d367481382a4b70c

解密之后:03501080220150052813

0 0