您的位置:首页 > 其它

有固定的密钥key的AES加密

2009-05-12 16:14 344 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: