Android AES Encrypt encrypt(Context context, String text)

Here you can find the source of encrypt(Context context, String text)

Description

encrypt

Declaration

public static String encrypt(Context context, String text)
            throws Exception 

Method Source Code

//package com.java2s;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import android.content.Context;
import android.content.pm.PackageManager;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Main {
    public static String encrypt(Context context, String text)
            throws Exception {
        byte[] message = Base64.encode(text.getBytes(), Base64.DEFAULT);
        SecretKey skeySpec = generateKey(getSeed(context),
                "edu.uoc.skeleton".getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(message);
        String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
        return result;
    }/*from   www .j av a 2  s  . c  o  m*/

    public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        final int iterations = 1000;

        final int outputKeyLength = 128;

        SecretKeyFactory secretKeyFactory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations,
                outputKeyLength);
        SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
        return secretKey;
    }

    private static char[] getSeed(Context context) {
        long installed = 0;
        try {
            installed = context.getPackageManager().getPackageInfo(
                    "edu.uoc.skeleton", 0).firstInstallTime;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return Long.toString(installed).toCharArray();
    }
}

Related

  1. encryptWithKey(String key, String src)
  2. crypt(byte[] text, byte[] key, int mode)
  3. aesEncode(String seed, String cleartext)
  4. encrypt(byte[] raw, byte[] clear)
  5. encrypt(Context context, String text)
  6. encryptedData(String userkey, String userData)
  7. encryptedPassword(String key, String userData)
  8. generateEncryptionSecret()
  9. encode(String seed, String cleartext)