編輯:關於 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 屬於對稱加密,密鑰一旦泄露便可被破解,因此密鑰的保管尤為關鍵。
Android 自定義 View 實作圓形 Progress 進度條
先看成果: 目標很明確:在一個圓框內部畫一段會持續增長的扇形。整體可以拆成四個步驟。 一、建立類別與自定義屬性 新增 ProgressView 繼承自 View
Android Notification 通知機制完整詳解
Notification 簡介 Notification 是顯示在手機狀態列的通知,代表一種具有全域效果的通知訊息,程式通常透過 NotificationManager
Android 網路編程 UDP 實戰(三):搜索區域網內的所有設備
承接前面的 UDP 主題,本篇主要探討如何在區域網中搜索所有設備。這個需求在物聯網應用中相當常見,也頗具綜合性,因此特別將它放進標題。文末再補充一些網路編程的常見問題。
Android 自定義 View 高級特效:神奇的貝塞爾曲線
效果預覽 效果圖中我們實現了一個隨手指滑動變化的二階貝塞爾曲線,還有一個能穿越所有已知點的複雜貝塞爾曲線。學會使用貝塞爾曲線後,可以做出 QQ 紅點滑動刪除、360 動