Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

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

編輯:關於 Android 程式設計

此前已經寫過常用的 MD5 加密算法,但一款自然不能满足需求。最近接觸到 AES 加密算法,作為美國聯邦政府采用的一種高級加密標準,聽名字就頗有分量。廢話少說,先學會用再深入。AES 屬於對稱加密算法,加密與解密使用同一把密鑰。

加密與解密的核心實現

/**
 * AES 加密算法加密
 */
public static String encrypt(String seed, String cleartext) throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext.getBytes());
    return toHex(result);
}
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);
    return cipher.doFinal(clear);
}
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();
}

/**
 * AES 加密算法解密
 */
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);
    return cipher.doFinal(encrypted);
}
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 和 256 位可能不可用
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

測試代碼

String masterPassword = "test";
String originalText = "0123456789";
String encryptingCode = SimpleCrypto.encrypt(masterPassword, originalText);
Log.i("加密結果為 ", encryptingCode);
String decryptingCode = SimpleCrypto.decrypt(masterPassword, encryptingCode);
Log.i("解密結果", decryptingCode);

需要提醒的是,由於 AES 屬於對稱加密,密鑰一旦泄露便可被破解,因此密鑰的保管尤為關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved