Android AES Encrypt encryptWithKey(String key, String src)

Here you can find the source of encryptWithKey(String key, String src)

Description

encrypt With Key

Declaration

public static HashMap<String, String> encryptWithKey(String key,
            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 java.util.HashMap;
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 = "aasdfVpg";
    private static final String ENCRYPTION_IV = "4e5WasdfasdfasEX";

    public static HashMap<String, String> encryptWithKey(String key,
            String src) {//w  w  w  .  j  a  v  a2s .  c  om
        HashMap<String, String> encryptionMap = new HashMap<String, String>();

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            encryptionMap.put("iv", ENCRYPTION_IV);
            cipher.init(Cipher.ENCRYPT_MODE, makeKey(key),
                    makeIv(encryptionMap.get("iv")));
            encryptionMap.put("encrypted", Base64.encodeToString(
                    cipher.doFinal(src.getBytes()), Base64.NO_WRAP));

            return encryptionMap;

        } 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. encryptHex(String content, String username, String password)
  2. encryptNumberWithAES(String number)
  3. encryptToBase64Text(String key, String src)
  4. encryptToBytes(String key, String src)
  5. encryptUrlEncode(String dataPassword, String cleartext)
  6. crypt(byte[] text, byte[] key, int mode)
  7. aesEncode(String seed, String cleartext)
  8. encrypt(byte[] raw, byte[] clear)
  9. encrypt(Context context, String text)