Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.math.BigInteger;

import java.security.spec.RSAPublicKeySpec;

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 PREF_PUBLIC_MOD = "PublicModulus";
    public static final String PREF_PUBLIC_EXP = "PublicExponent";
    public static final String DEFAULT_PREF = "";

    public static RSAPublicKeySpec getRecipientsPublicKey(String contactNum, Context context) {
        Log.w(TAG, "retrieving public key for contact " + contactNum);
        SharedPreferences prefs = context.getSharedPreferences(contactNum, Context.MODE_PRIVATE);

        String pubMod = prefs.getString(PREF_PUBLIC_MOD, DEFAULT_PREF);
        String pubExp = prefs.getString(PREF_PUBLIC_EXP, DEFAULT_PREF);
        Log.w(TAG, "the public modulus is " + pubMod + " and exponent is " + pubExp + " for " + contactNum);
        // String recipient = prefs.getString(PREF_RECIPIENT_NUM, DEFAULT_PREF);
        if (!pubMod.isEmpty() && !pubExp.isEmpty()) {
            Log.i(TAG, "great! public key found for " + contactNum + " with modulus " + pubMod + " and exponent "
                    + pubExp);
            byte[] pubModBA = Base64.decode(pubMod, Base64.DEFAULT);
            byte[] pubExpBA = Base64.decode(pubExp, Base64.DEFAULT);
            BigInteger pubModBI = new BigInteger(1, pubModBA); // 1 is added as
            // an attempt to
            // deal with
            // com.android.org.bouncycastle.crypto.DataLengthException:
            // input too
            // large for RSA
            // cipher
            BigInteger pubExpBI = new BigInteger(1, pubExpBA);
            Log.i(TAG, "public modulus is " + pubModBI + " and public exponent is " + pubExpBI + " in base 256 "
                    + pubModBA + " " + pubExpBA);

            // do I need to catch any exception for the following?
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(pubModBI, pubExpBI);
            // X509EncodedKeySpec publicKeySpec = new
            // X509EncodedKeySpec(encodedKey);

            return pubKeySpec;
        }
        Log.w(TAG, "recipient's public key not found");
        return null;

    }
}