加密解密,秘钥相同。
加密后得到的字节数组,不可以直接转成字符串,因为使用字符串转回字节数组的时候,字节数组发生变化。可以把字节数组使用算法转成十六进制字符串,解密时候先把十六进制字符串转成字节数组。
package codeUtil;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESCodeUtil {
public static byte[] aesEncode(String msg,String password){
byte[] res=null;
try {
KeyGenerator instance = KeyGenerator.getInstance("AES");
instance.init(128, new SecureRandom(password.getBytes("utf-8")));
SecretKey secrKey = instance.generateKey();
byte[] encodFormat = secrKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(encodFormat, "AES");
Cipher instance2 = Cipher.getInstance("AES");
instance2.init(Cipher.ENCRYPT_MODE, key);
res=instance2.doFinal(msg.getBytes("utf-8"));
} catch (Exception e) {
System.out.println("encode error");
}
return res;
}
public static byte[] aesDecode(byte[] msg,String password){
byte[] res=null;
try {
KeyGenerator instance = KeyGenerator.getInstance("AES");
instance.init(128, new SecureRandom(password.getBytes("utf-8")));
SecretKey generateKey = instance.generateKey();
byte[] encodedFormat = generateKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(encodedFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
res=cipher.doFinal(msg);
} catch (Exception e) {
// TODO: handle exception
}
return res;
}
public static String byteToHexStr(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 byte[] hexStrToBytes(String str){
if(str.length()<1){
return null;
}
byte[] res=new byte[str.length()/2];
for(int i=0;i<res.length;i++){
int high=Integer.parseInt(str.substring(i*2, i*2+1),16);
int low=Integer.parseInt(str.substring(i*2+1, i*2+2),16);
res[i]=(byte)(high*16+low);
}
return res;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String password="123";
byte[] msg = aesEncode("abc", password);
String str = byteToHexStr(msg);
System.out.println(str);
byte[] res=hexStrToBytes(str);
byte[] aesDecode = aesDecode(res, password);
System.out.println(new String(aesDecode,"utf-8"));
}
}