Decrypts a given encrypted text with a given password, salt and initialization vector - Android java.security

Android examples for java.security:Password

Description

Decrypts a given encrypted text with a given password, salt and initialization vector

Demo Code


//package com.java2s;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main {
    private static int pswdIterations = 2048;
    private static int keySize = 256;

    /**//from   w ww  .  j a  va 2 s. c om
     * Decrypts a given encrypted text with a given password, salt and initialization vector
     * 
     * @param encryptedText
     * @param password
     * @param salt
     * @param initializationVector
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, String password,
            String salt, String initializationVector) throws Exception {

        // Convert Strings back to byte arrays
        byte[] saltBytes = salt.getBytes("UTF-8");
        byte[] encryptedTextBytes = Base64.decode(encryptedText,
                Base64.NO_WRAP);
        byte[] ivBytes = Base64
                .decode(initializationVector, Base64.NO_WRAP);

        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes,
                pswdIterations, keySize);

        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(),
                "AES");

        // Decrypt the message
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(
                ivBytes));

        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return new String(decryptedTextBytes);
    }
}

Related Tutorials