1. 程式人生 > >AES加密解密 附贈 base64

AES加密解密 附贈 base64

   AES加密是一總比較常用的,會補足長度的加密方式,不管你長度為多少,加密完之後都會變成128位(僅指這裡,當然也有其他的AES)。 
   敲黑板:之前做過一次跨語言的加密解密,發現是不可以的。即java php c++之間不同的加密解密不要通用,因為進位制和編碼的問題,如果強行使用的話。需要二進位制十六進位制八進位制各種換算 - -。  我這麼懶,當然沒有去做。
   而且任何加密後的內容是沒有辦法看到的,如果要顯示,統統需要base64處理。

程式碼片如下:
public static byte[] AESdecrypt(byte[] input , String key){
            byte[] output = null;
try{ javax.crypto.spec.SecretKeySpec skey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES"); javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, skey);
output = cipher.doFinal(input); } catch (Exception e) { System.out.println(e.toString()); } return output; } //AES的加密部分 public static byte[] AESencrypt(byte[] input , String key) throws Exception{ byte[] crypted = null; try{ javax.crypto
.spec.SecretKeySpec skey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES"); javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input); }catch(Exception e){ System.out.println(e.toString()); } return crypted; } //base64解密部分 public static String Base64decrypt(String input){ return new String(org.apache.commons.codec.binary.Base64.decodeBase64(input.getBytes())); } //base64加密部分 public static String Base64encrypt(String input){ return new String(org.apache.commons.codec.binary.Base64.encodeBase64(input.getBytes())); }