Android AES Encrypt encrypt(String src)

Here you can find the source of encrypt(String src)

Description

encrypt

Declaration

public static String encrypt(String src) 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main {
    private static final String ENCRYPTION_KEY = "Rwasdfpg";
    private static final String ENCRYPTION_IV = "4easdfasdfasdFEX";

    public static String encrypt(String src) {
        try {/*from  w ww  . ja v a 2s .c  o m*/
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, makeKey(), makeIv());
            return Base64.encodeToString(cipher.doFinal(src.getBytes()),
                    Base64.NO_WRAP);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static Key makeKey() {
        return makeKey(ENCRYPTION_KEY);
    }

    static Key makeKey(String passkey) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] key = md.digest(passkey.getBytes("UTF-8"));
            return new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    static AlgorithmParameterSpec makeIv() {
        return makeIv(ENCRYPTION_IV);
    }

    static AlgorithmParameterSpec makeIv(String ivString) {
        try {
            return new IvParameterSpec(ivString.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. encrypt(String key, String src)
  2. encrypt(String key, String src)
  3. encrypt(String seed, String clearText)
  4. encrypt(String seed, String clearText)
  5. encrypt(String seed, String cleartext)
  6. encrypt(String src)
  7. encrypt(String text, String key)
  8. encrypt(byte[] content, String key)
  9. encrypt(byte[] content, String password)