Skip to content

Instantly share code, notes, and snippets.

@luoka
Last active August 28, 2018 06:18
Show Gist options
  • Select an option

  • Save luoka/f83c875132ecbe6feb7e2d02a010a2c8 to your computer and use it in GitHub Desktop.

Select an option

Save luoka/f83c875132ecbe6feb7e2d02a010a2c8 to your computer and use it in GitHub Desktop.
AES加密解密
public class AESUtil
{
private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(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 SecretKeySpec getKey(String myKey){
MessageDigest sha = null;
try {
byte[] key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
String s = parseByte2HexStr(key);
String substring = s.substring(0, 16);
String s1 = substring.toLowerCase();
SecretKeySpec secretKey = new SecretKeySpec(s1.getBytes(),"AES");
return secretKey;
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.getMessage(),e);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(),e);
}
return null;
}
/**
* 加密
* @param strToEncrypt
* @return
*/
public static String encrypt(String strToEncrypt,String password)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, getKey(password));
return Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
LOGGER.error(e.getMessage(),e);
}
return null;
}
/**
* 解密
* @param strToDecrypt
* @return
*/
public static String decrypt(String strToDecrypt,String password)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE,getKey(password));
return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
}
catch (Exception e)
{
LOGGER.error(e.getMessage(),e);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment