Java tutorial
//package com.java2s; import java.math.BigInteger; import java.security.spec.RSAPrivateKeySpec; import android.content.Context; import android.content.SharedPreferences; import android.util.Base64; import android.util.Log; public class Main { private static final String TAG = "MyKeyUtils"; public static final String PREFS_MY_KEYS = "MyKeys"; public static final String PREF_PRIVATE_MOD = "PrivateModulus"; public static final String PREF_PRIVATE_EXP = "PrivateExponent"; public static void savePrivateKey(RSAPrivateKeySpec privateKey, Context context) { BigInteger privateModBI = privateKey.getModulus(); BigInteger privateExpBI = privateKey.getPrivateExponent(); byte[] privateModBA = privateModBI.toByteArray();// Base64.encodeInteger(pubModBI); // // for some // strange reason // this throws // NoSuchMethodError byte[] privateExpBA = privateExpBI.toByteArray();// Base64.encodeInteger(pubExpBI); try { String privateModBase64Str = Base64.encodeToString(privateModBA, Base64.NO_WRAP); String privateExpBase64Str = Base64.encodeToString(privateExpBA, Base64.NO_WRAP); savePrivateKey(privateModBase64Str, privateExpBase64Str, context); } catch (NoSuchMethodError e) { Log.e(TAG, "Base64.encode() method not available", e); } } private static void savePrivateKey(String mod, String exp, Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_MY_KEYS, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putString(PREF_PRIVATE_MOD, mod); prefsEditor.putString(PREF_PRIVATE_EXP, exp); // prefsEditor.putString(PREF_PRIVATE_MOD, DEFAULT_PRIVATE_MOD); prefsEditor.commit(); } }