Android Password Encrypt encrypt(String password, String data)

Here you can find the source of encrypt(String password, String data)

Description

encrypt

License

Open Source License

Declaration

public static String encrypt(String password, String data)
            throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main {
    private static final String CIPHER_ALGORITHM = "AES";
    private static final String RANDOM_GENERATOR_ALGORITHM = "SHA1PRNG";
    private static final int RANDOM_KEY_SIZE = 128;

    public static String encrypt(String password, String data)
            throws Exception {

        byte[] secretKey = generateKey(password.getBytes());
        byte[] clear = data.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey,
                CIPHER_ALGORITHM);/*from   w w w.  j  a v  a2s.  c  o  m*/
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        String encryptedString = Base64.encodeToString(encrypted,
                Base64.DEFAULT);
        return encryptedString;
    }

    public static byte[] generateKey(byte[] seed) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator
                .getInstance(CIPHER_ALGORITHM);
        SecureRandom secureRandom = SecureRandom
                .getInstance(RANDOM_GENERATOR_ALGORITHM);
        secureRandom.setSeed(seed);
        keyGenerator.init(RANDOM_KEY_SIZE, secureRandom);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }
}

Related

  1. encryptionKey(String password)
  2. encryptionKey(String password)