- 最近项目中用到自己公司开放平台上的AES加密,(针对密码要做加密),具体加密规则如下:
二、具体工具类如下,直接拿去用
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
*
* @author xxx
*
* Android AES加密
* 填充:PKCS7Padding
* 加密模式ECB
*
*/
public class AESUtil {
/**
* encrypt input text
*
* @param password 密码
* @param username 用户名,长度16(如果超过16位则截取前16位,不足16为后面补0)
* @return
*/
public static String encrypt(String password, String username) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(username.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(password.getBytes());
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
return new String(Base64.encodeBase64(crypted));
}
/**
* decrypt input text
*
* @param input
* @param key
* @return
*/
public static String decrypt(String input, String key) {
byte[] output = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
// output = cipher.doFinal(Base64.decodeBase64(input));
output = cipher.doFinal(Hex.decodeHex(input.toCharArray()));
} catch (Exception e) {
System.out.println(e.toString());
}
return new String(output);
}
}
三、 使用中可以写一个测试例子验证下,结果验证可以直接去这个网站对比:线加密网址:http://tool.chacuo.net/cryptaes/
结语:欧了,完活!