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;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.SecretKey;
import javax.crypto.NoSuchPaddingException;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;

public class Main {
    private static final String LOG_TAG = "MarvinMessaging";
    private static final String KEY_FACTORY = "PBEWithSHA256And128BitAES-CBC-BC";
    private static final int ITERATION_COUNT = 50;
    private static final byte[] messageSalt = { (byte) 0xfc, (byte) 0x76, (byte) 0x80, (byte) 0xae, (byte) 0xfd,
            (byte) 0x82, (byte) 0xbe, (byte) 0xee, };
    public static Cipher messageEncryptionCipher;
    public static Cipher messageDecryptionCipher;

    public static void genMessageCiphers(char[] pass) {
        try {
            messageEncryptionCipher = genCipher(pass, messageSalt, KEY_FACTORY, ITERATION_COUNT,
                    Cipher.ENCRYPT_MODE);
            messageDecryptionCipher = genCipher(pass, messageSalt, KEY_FACTORY, ITERATION_COUNT,
                    Cipher.DECRYPT_MODE);
        } catch (Exception e) {
            Log.d(LOG_TAG, "genStorageCiphers", e);
        }
    }

    private static Cipher genCipher(char[] pass, byte[] salt, String factory, int iterations, int mode)
            throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException {
        PBEKeySpec keySpec = new PBEKeySpec(pass, salt, iterations, 128);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(factory);
        SecretKey key = keyFactory.generateSecret(keySpec);
        AlgorithmParameterSpec spec = new PBEParameterSpec(salt, iterations);
        Cipher cipher = Cipher.getInstance(factory);
        cipher.init(mode, key, spec);
        return cipher;
    }
}