Created
October 21, 2019 11:59
-
-
Save codethereforam/f1d6f50152be0f05eb26728986d7c807 to your computer and use it in GitHub Desktop.
AES加密解密工具
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* AES utility | |
* | |
* @author yanganyu | |
* @date 2019/9/18 21:01 | |
*/ | |
public class AesUtil { | |
private static SecretKeySpec secretKey; | |
private AesUtil() { | |
} | |
private static void setKey(String myKey) { | |
try { | |
byte[] key = myKey.getBytes(StandardCharsets.UTF_8); | |
MessageDigest sha = MessageDigest.getInstance("SHA-1"); | |
key = sha.digest(key); | |
key = Arrays.copyOf(key, 16); | |
secretKey = new SecretKeySpec(key, "AES"); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static String encrypt(String strToEncrypt, String secret) { | |
try { | |
setKey(secret); | |
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); | |
cipher.init(Cipher.ENCRYPT_MODE, secretKey); | |
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); | |
} catch (Exception e) { | |
throw new RuntimeException("Error while encrypting", e); | |
} | |
} | |
public static String decrypt(String strToDecrypt, String secret) { | |
try { | |
setKey(secret); | |
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); | |
cipher.init(Cipher.DECRYPT_MODE, secretKey); | |
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); | |
} catch (Exception e) { | |
throw new RuntimeException("Error while decrypting", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment