Encrypts the passed in String. - Android java.security

Android examples for java.security:Password

Description

Encrypts the passed in String.

Demo Code


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

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static final String STR_UTF_8 = "UTF-8";
    public static final String STR_AES_CBC_PKCS5Padding = "AES/CBC/PKCS5Padding";

    /**/*from w  w  w . j  a  v  a 2  s  .co  m*/
     * Encrypts the passed in String.
     * @param aStringEncrypted - string that will be decrypted.
     * @param aBytesPassword - password that will be used for the decryption.
     * @param aIV - initialization vector.
     * @return String - decrypted string.
     */
    public static String getDecryptedCBC(String aStringEncrypted,
            byte[] aBytesPassword, byte[] aIV) throws Exception {
        byte[] bytes = Base64.decode(aStringEncrypted.getBytes(STR_UTF_8),
                Base64.DEFAULT);
        byte[] decryptedData = decryptCBC(aBytesPassword, bytes,
                STR_AES_CBC_PKCS5Padding, aIV);
        String strDecrypted = new String(decryptedData, STR_UTF_8);
        return strDecrypted;
    }

    public static byte[] decryptCBC(byte[] aBytesKey, byte[] encrypted,
            String aAlgorithm, byte[] aIV) throws Exception {
        IvParameterSpec ivParams = new IvParameterSpec(aIV);
        SecretKeySpec skeySpec = new SecretKeySpec(aBytesKey, aAlgorithm);
        Cipher cipher = Cipher.getInstance(aAlgorithm);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParams);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
}

Related Tutorials