Android AES Encrypt encrypt(String content, String password)

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

Description

encrypt

Declaration

public static byte[] encrypt(String content, String password)
        throws java.security.InvalidKeyException 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {

    public static byte[] encrypt(String content, String password)
            throws java.security.InvalidKeyException {
        try {//from  w  ww .  j a v a2  s.c  o m
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(byteContent);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. encrypt(String cleartext)
  2. encrypt(String content, String password)
  3. encrypt(String content, String password)
  4. encrypt(String content, String password)
  5. encrypt(String data)
  6. encrypt(String dataPassword, String cleartext)
  7. encrypt(String key, String src)
  8. encrypt(String key, String src)