Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android加密算法之AES加密和解密實現

Android加密算法之AES加密和解密實現

編輯:關於Android編程

前面寫了常用了MD5加密算法,一個肯定不能滿足本屌絲的胃口,最近發現AES加密算法貌似挺牛逼的樣子,還是是美國聯邦政府采用的一種區塊高級加密標准,一看到“高級”就把我嚇尿了,果然牛逼,廢話少說,先學會用再說。


/**
  * @param
  * @return AES加密算法加密
  * @throws Exception
  */
 public static String encrypt(String seed, String cleartext)
   throws Exception {
  byte[] rawKey = getRawKey(seed.getBytes());
  byte[] result = encrypt(rawKey, cleartext.getBytes());
  return toHex(result);
 }
 /**
  * @param
  * @return AES加密算法加密
  * @throws Exception
  */
 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  byte[] encrypted = cipher.doFinal(clear);
  return encrypted;
 }
 private static String toHex(byte[] buf) {
  final String HEX = "0123456789ABCDEF";
  if (buf == null)
   return "";
  StringBuffer result = new StringBuffer(2 * buf.length);
  for (int i = 0; i < buf.length; i++) {
   result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append(
     HEX.charAt(buf[i] & 0x0f));
  }
  return result.toString();
 }
 /**
  * @param raw
  * @param encrypted
  * @return AES加密算法解密
  * @throws Exception
  */
 public static String decrypt(String seed, String encrypted)
   throws Exception {
  byte[] rawKey = getRawKey(seed.getBytes());
  byte[] enc = toByte(encrypted);
  byte[] result = decrypt(rawKey, enc);
  return new String(result);
 }
 private static byte[] decrypt(byte[] raw, byte[] encrypted)
   throws Exception {
  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  byte[] decrypted = cipher.doFinal(encrypted);
  return decrypted;
 }
 private static byte[] toByte(String hexString) {
  int len = hexString.length() / 2;
  byte[] result = new byte[len];
  for (int i = 0; i < len; i++)
   result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
     16).byteValue();
  return result;
 }
 private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128, sr); // 192 and 256 bits may not be available
  SecretKey skey = kgen.generateKey();
  byte[] raw = skey.getEncoded();
  return raw;
 }
測試代碼:
        String masterPassword = "test";  
        String originalText = "0123456789";
        String encryptingCode = SimpleCrypto.encrypt(masterPassword,originalText);  
        Log.i("加密結果為 ",encryptingCode);  
        String decryptingCode = SimpleCrypto.decrypt(masterPassword, encryptingCode);
        Log.i("解密結果",decryptingCode);  

PS:AES屬於對稱加密方法,可破解有木有!
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved