Java tutorial
//package com.java2s; /* Copyright Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import android.util.Base64; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Main { public static String encrypt(String key, String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String aesKey; aesKey = key.substring(0, 16); Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, AESkey(key), new IvParameterSpec(aesKey.getBytes())); byte[] encrypted = c.doFinal(str.getBytes("UTF-8")); String enStr = new String(Base64.encodeToString(encrypted, 0)); return enStr; } private static Key AESkey(String key) throws UnsupportedEncodingException { String aesKey; aesKey = key.substring(0, 16); byte[] keyBytes = new byte[16]; byte[] b = aesKey.getBytes("UTF-8"); int len = b.length; if (len > keyBytes.length) { len = keyBytes.length; } System.arraycopy(b, 0, keyBytes, 0, len); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); return keySpec; } }