依赖Apache的commons-codec-1.9.jar
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| package utils;
import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.SecureRandom;
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES {
public static String encrypt(String content, String password) throws GeneralSecurityException, UnsupportedEncodingException { byte[] byteContent = content.getBytes("utf-8"); return Base64.encodeBase64String(doFinal(byteContent, password, Cipher.ENCRYPT_MODE)); }
public static String decrypt(String content, String password) throws GeneralSecurityException { byte[] byteContent = Base64.decodeBase64(content); return new String(doFinal(byteContent, password, Cipher.DECRYPT_MODE)); }
private static byte[] doFinal(byte[] byteContent, String password, int mode) throws GeneralSecurityException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(mode, key); return cipher.doFinal(byteContent); } }
|