Android AES Encrypt encryptToBase64Text(String key, String src)

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

Description

encrypt To Base Text

Declaration

public static String encryptToBase64Text(String key, String src)
            throws Exception 

Method Source Code

//package com.java2s;
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 {
    public static String encryptToBase64Text(String key, String src)
            throws Exception {
        byte[] result = encryptToBytes(key, src);
        return new String(Base64.encode(result, Base64.DEFAULT));
    }//www . ja  va 2s . c  o m

    public static byte[] encryptToBytes(String key, String src)
            throws Exception {
        byte[] rawKey = getRawKey(key);
        return encrypt(rawKey, src.getBytes());
    }

    private static byte[] getRawKey(String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(key.getBytes());
        kgen.init(256, sr);
        SecretKey skey = kgen.generateKey();
        return skey.getEncoded();
    }

    private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        return cipher.doFinal(src);
    }
}

Related

  1. encryptBytes(String seed, byte[] cleartext)
  2. encryptBytes(byte[] data, byte[] key)
  3. encryptHex(String content, String key)
  4. encryptHex(String content, String username, String password)
  5. encryptNumberWithAES(String number)
  6. encryptToBytes(String key, String src)
  7. encryptUrlEncode(String dataPassword, String cleartext)
  8. encryptWithKey(String key, String src)
  9. crypt(byte[] text, byte[] key, int mode)