オブジェクトシーケンス逆シーケンス化AES暗号化後Base 64処理
3057 ワード
/**
* AES
* @param content *
* @param key *
* @return
*/
public static byte[] encrypt(byte[] content, String key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");//
byte[] byteContent = content;
cipher.init(Cipher.ENCRYPT_MODE, keySpec);//
byte[] result = cipher.doFinal(byteContent);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* AES
* @param content
* @param key
* @return
*/
public static byte[] decrypt(byte[] content, String key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");//
cipher.init(Cipher.DECRYPT_MODE, keySpec);//
byte[] result = cipher.doFinal(content);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
*
*/
public static String object2String(Object o) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
byte[] byteArray = baos.toByteArray();
byteArray = encrypt(byteArray,key);
String str = Base64.encode(byteArray);
return str;
}
/**
*
*/
public static Object string2Object(String info) throws Exception {
byte[] byteArray = Base64.decode(info);
byteArray = decrypt(byteArray,key);
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}