AES是一种对称加密方式,比DES更为安全,用一个秘钥加密数据之后,可以用同一个秘钥对加密后的数据解密还原,以下是一套以字符串为例子的使用全过程演示,
用到了
commons-codec.jar
1 package testEncrypt; 2 3 import java.security.InvalidKeyException; 4 import java.security.Key; 5 import java.security.NoSuchAlgorithmException; 6 import java.security.SecureRandom; 7 8 import javax.crypto.BadPaddingException; 9 import javax.crypto.Cipher; 10 import javax.crypto.IllegalBlockSizeException; 11 import javax.crypto.KeyGenerator; 12 import javax.crypto.NoSuchPaddingException; 13 import javax.crypto.SecretKey; 14 import javax.crypto.spec.SecretKeySpec; 15 16 import org.apache.commons.codec.binary.Base64; 17 //import sun.misc.BASE64Encoder; 18 public class TestAesEncrypt { 19 20 public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { 21 //随机生成密钥 22 KeyGenerator keygen = KeyGenerator.getInstance("AES"); 23 //SecureRandom random = new SecureRandom(Base64.decodeBase64("abc")); 24 SecureRandom random = new SecureRandom(); 25 keygen.init(random); 26 Key key = keygen.generateKey(); 27 //获取秘钥字符串 28 String key64Str = Base64.encodeBase64String(key.getEncoded()); 29 //要加密的数据 30 String dataStr="da89gh9qj3ebg9babjdslgbuqgb&FTUG^(GB"; 31 System.out.println("要加密的数据:"+dataStr); 32 33 //还原秘钥字符串到秘钥byte数组 34 byte[] keyByteArray = Base64.decodeBase64(key64Str); 35 //重新形成秘钥,SecretKey是Key的子类 36 SecretKey secretKey = new SecretKeySpec(keyByteArray, "AES"); 37 38 //初始化加密组件 39 Cipher cipher = Cipher.getInstance("AES"); 40 cipher.init(Cipher.ENCRYPT_MODE, secretKey); 41 42 //加密后的数据,首先将字符串转为byte数组,然后加密,为便于保存先转为base64 43 String encryptedDataStr = Base64.encodeBase64String(cipher.doFinal(dataStr.getBytes())); 44 System.out.println("加密后的数据:"+encryptedDataStr); 45 46 //将加密组件的模式改为解密 47 cipher.init(Cipher.DECRYPT_MODE, secretKey); 48 //和上面的加密相反,先解base64,再解密,最后将byte数组转为字符串 49 String decodeDataStr = new String(cipher.doFinal(Base64.decodeBase64(encryptedDataStr))); 50 System.out.println("解密后的数据:"+decodeDataStr); 51 } 52 53 }