Android examples for Account:Account Information
save Account information using DES to a Properties file
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.Key; import java.security.spec.AlgorithmParameterSpec; import java.util.Properties; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import android.text.TextUtils; public class Main { public static final String filePath = "cookie.prop"; public static final String PRIVATEKEY = "asdfasdf"; public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding"; public static final String KEY1 = "mobileNo"; public static final String KEY2 = "password"; public static final String comment = "Account"; public static boolean saveAccount(String mobileNo, String pwd) { writeProperties(encode(PRIVATEKEY, mobileNo), encode(PRIVATEKEY, pwd)); return true;//from w w w . j a v a 2s.c om } public static void writeProperties(String value1, String value2) { if (TextUtils.isEmpty(value1) || TextUtils.isEmpty(value2)) { return; } FileInputStream fis = null; FileOutputStream fos = null; File f = new File(filePath); try { if (!f.exists() || !f.isFile()) { f.createNewFile(); } fis = new FileInputStream(f); Properties p = new Properties(); p.load(fis); p.setProperty(KEY1, value1); p.setProperty(KEY2, value2); fos = new FileOutputStream(f); p.store(fos, comment); } catch (Exception e) { } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static String encode(String key, String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); byte[] bytes = cipher.doFinal(data.getBytes()); return byte2hex(bytes); } catch (Exception e) { e.printStackTrace(); return data; } } private static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); } }