AES Decrypts into plain text - Android java.security

Android examples for java.security:AES

Description

AES Decrypts into plain text

Demo Code


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

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static final int ITERATIONS = 1000;
    private static final int KEY_LENGTH = 256;
    private static final String SECRET_KEY_ALGORITHM = "PBKDF2WithHmacSHA1";
    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String TEXT_ENCODING = "UTF-8";
    private static final String SEPARATOR = ",";

    /**//from ww w . j  ava  2s  .  c o m
     * Decrypts into plain text
     * @param password key password
     * @param encryptedData text to decrypt
     * @throws Exception
     */
    public static String decryptData(char[] password, String encryptedData)
            throws Exception {

        // Split the string into its requisite parts
        final String[] pieces = encryptedData.split(SEPARATOR);
        byte[] data = Base64.decode(pieces[0], Base64.DEFAULT);
        byte[] initVector = Base64.decode(pieces[1], Base64.DEFAULT);
        byte[] salt = Base64.decode(pieces[2], Base64.DEFAULT);

        final Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        final IvParameterSpec ivParameterSpec = new IvParameterSpec(
                initVector);
        final SecretKey secretKey = generateSecretKey(password, salt);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        return new String(cipher.doFinal(data), TEXT_ENCODING);
    }

    /**
     * Generates a secret key
     * @param password passphrase for the key
     * @param salt a salt for the password
     */
    public static SecretKey generateSecretKey(char[] password, byte[] salt)
            throws Exception {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory
                .getInstance(SECRET_KEY_ALGORITHM);
        final KeySpec keySpec = new PBEKeySpec(password, salt, ITERATIONS,
                KEY_LENGTH);
        byte[] keyBytes = secretKeyFactory.generateSecret(keySpec)
                .getEncoded();
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }
}

Related Tutorials