Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.util.Log;

import javax.crypto.Cipher;

public class Main {
    private static final String LOG_TAG = "MarvinMessaging";
    public static Cipher storageDecryptionCipher;
    public static Cipher messageDecryptionCipher;

    public static CharSequence decryptMessageText(String ciphertext) {
        return decryptText(ciphertext, messageDecryptionCipher);
    }

    public static CharSequence decryptText(String ciphertextString) {
        return decryptText(ciphertextString, storageDecryptionCipher);
    }

    private static CharSequence decryptText(String ciphertextString, Cipher cipher) {
        byte[] ciphertext = hexStringToBytes(ciphertextString);
        byte[] plaintext = {};

        //can't decrypt an empty string...exceptions gallore
        if (ciphertextString.length() == 0)
            return (CharSequence) ciphertextString;

        try {
            plaintext = cipher.doFinal(ciphertext);
        } catch (Exception e) {
            Log.d(LOG_TAG, "decryptText", e);
        }

        //TODO: dont' convert to string as interim...insecure
        return (CharSequence) (new String(plaintext));
    }

    public static byte[] hexStringToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        int j = 0;

        for (int i = 0; i < hex.length(); i += 2) {
            try {
                String hexByte = hex.substring(i, i + 2);
                Integer I = new Integer(0);
                I = Integer.decode("0x" + hexByte);
                int k = I.intValue();
                bytes[j++] = new Integer(k).byteValue();
            } catch (NumberFormatException e) {
                Log.d(LOG_TAG, "hexStringToBytes", e);
                return bytes;
            } catch (StringIndexOutOfBoundsException e) {
                Log.d(LOG_TAG, "hexStringToBytes", e);
                return bytes;
            }
        }
        return bytes;
    }
}