Initializes the encryption and decryption ciphers that will be used to create the appropriate cipher streams. - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

Initializes the encryption and decryption ciphers that will be used to create the appropriate cipher streams.

Demo Code


//package com.java2s;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;

import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static String KEY_ALGORITHM = "AES";
    private static byte[] iv = { (byte) 0xc1, (byte) 0x1d, (byte) 0x53,
            (byte) 0xf0, (byte) 0x02, (byte) 0xf4, (byte) 0x8b,
            (byte) 0x33, (byte) 0x96, (byte) 0x7e, (byte) 0xa3,
            (byte) 0x2e, (byte) 0xb4, (byte) 0x1f, (byte) 0x56, (byte) 0x70 };
    private static Cipher ecipher;
    private static Cipher dcipher;

    /**//from   ww  w.j a v a 2  s .  c o m
     * Initializes the encryption and decryption ciphers that will be used
     * to create the appropriate cipher streams.
     * @param pass
     */
    public static void init(String pass) {
        try {
            //Converts the password into a 128 bit byte array
            byte[] passBytes = padPass(pass);
            //Generates a key object based on the password
            SecretKeySpec key = new SecretKeySpec(passBytes, KEY_ALGORITHM);
            //SecretKey key = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec);

            ecipher = Cipher.getInstance(ALGORITHM);
            dcipher = Cipher.getInstance(ALGORITHM);

            ecipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
    }

    private static byte[] padPass(String pass) {
        String padded = "";

        if (pass.length() >= 16)
            padded = pass.substring(0, 16);
        else {
            padded = pass;

            while (padded.length() < 16)
                padded += "a";
        }

        return padded.getBytes();
    }
}

Related Tutorials