Last active
August 30, 2018 07:21
-
-
Save wooramel/4f3abd7da3d996ebf7e4dc4328543455 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.io.IOException; | |
import java.io.UnsupportedEncodingException; | |
import java.security.GeneralSecurityException; | |
import java.util.Base64; | |
/** | |
* 简单的 AES 对称加密 | |
* | |
* @author mingcheng | |
*/ | |
public class AESEncrypttUtil { | |
private static final String KEY_ALGORITHM = "AES"; | |
private static AESEncrypttUtil instance; | |
// 使用的时候请更改,需要 16 位长度 | |
final static String encryptionKey = "0123456789abcdef"; | |
private final Cipher cipher; | |
private AESEncrypttUtil() throws GeneralSecurityException { | |
cipher = Cipher.getInstance(KEY_ALGORITHM); | |
} | |
public static AESEncrypttUtil getInstance() throws GeneralSecurityException { | |
if (instance == null) { | |
instance = new AESEncrypttUtil(); | |
} | |
return instance; | |
} | |
public String encrypt(String plainText, String encryptionKey) throws GeneralSecurityException, UnsupportedEncodingException { | |
SecretKeySpec spec = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), KEY_ALGORITHM); | |
cipher.init(Cipher.ENCRYPT_MODE, spec); | |
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); | |
return Base64.getEncoder().encodeToString(encryptedBytes); | |
} | |
public String decrypt(String cipherText, String encryptionKey) throws GeneralSecurityException, IOException { | |
SecretKeySpec spec = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), KEY_ALGORITHM); | |
cipher.init(Cipher.DECRYPT_MODE, spec); | |
byte[] cipherTextBytes = Base64.getDecoder().decode(cipherText); | |
byte[] decValue = cipher.doFinal(cipherTextBytes); | |
return new String(decValue); | |
} | |
public String encrypt(String s) throws GeneralSecurityException, UnsupportedEncodingException { | |
return encrypt(s, encryptionKey); | |
} | |
public String decrypt(String s) throws GeneralSecurityException, IOException { | |
return decrypt(s, encryptionKey); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment