Encrypts a given text with a given password. - Android java.security

Android examples for java.security:Password

Description

Encrypts a given text with a given password.

Demo Code


//package com.java2s;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;

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;
import android.util.Base64;

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

    /**/*w w  w .j a  va  2s.  c  om*/
     * Encrypts a given text with a given password. The return value is an array of Strings containing the encrypted text (0), the salt (1)
     * and the initialization vector (2)
     * 
     * @param plainText
     * @param password
     * @return String[]
     * @throws Exception
     */
    public static String[] encrypt(String plainText, String password)
            throws Exception {

        // Get the salt
        String salt = generateSalt();
        byte[] saltBytes = salt.getBytes("UTF-8"); // Convert bytes to string

        // 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");

        // Encrypt the message
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        AlgorithmParameters params = cipher.getParameters();
        byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class)
                .getIV();
        byte[] encryptedTextBytes = cipher.doFinal(plainText
                .getBytes("UTF-8"));

        // Store the encrypted key, the salt and the initialization vector in an array
        String[] retVal = new String[3];
        retVal[0] = Base64.encodeToString(encryptedTextBytes,
                Base64.NO_WRAP); // Convert bytes to string
        retVal[1] = salt;
        retVal[2] = Base64.encodeToString(ivBytes, Base64.NO_WRAP); // Convert bytes to string
        return retVal;
    }

    private static String generateSalt() {
        // Generate a random salt
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        String s = new String(bytes);
        return s;
    }
}

Related Tutorials