Java tutorial
//package com.java2s; /* * Copyright (C) 2010 Giesecke & Devrient GmbH * * 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 javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import android.util.Log; public class Main { /** * Tag for logging */ private static final String TAG = "Helper"; /** * flag to indicate if the crypto-algorithms is initialized. * This should only be done once, during a multi-part crypto-operation */ private static boolean encryptInitialized = false; /** * Cipherobject to make encrypt operations */ private static Cipher encryptCipher; /** * This method should be used to encrypt a block of data. * * @param fileData * the data to encrypt. * @param encryptionKey * the key to initialize the cipher-algorithm. * @param encryptCompleted * a flag, that indicates, that a multi-part encryption is to be * completed. e.g. false, if the fileData consist of multiple * parts. true, if the fileData consists only of one single part * and so they could be encrypted in one operation. * * @return the encrypted data. */ public static byte[] encryptData(byte[] fileData, byte[] encryptionKey, boolean encryptCompleted) { // Initializing may only be done at the start of a multi-part crypto-operation. // if it's a single part crypto-operation initialization must always be done. if (!encryptInitialized) { // Initializing the cipher try { encryptCipher = Cipher.getInstance("AES"); } catch (Exception e) { Log.e(TAG, "Error while initializing encryption."); return null; } try { SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES"); encryptCipher.init(Cipher.ENCRYPT_MODE, keySpec); } catch (Exception e) { Log.e(TAG, "Error while initializing encryption."); return null; } encryptInitialized = true; } // encrypting try { if (!encryptCompleted) // done in case of multi-part operation fileData = encryptCipher.update(fileData); else // done in case of single part operation or to finish a multi-part operation fileData = encryptCipher.doFinal(fileData); } catch (Exception e) { Log.e(TAG, "Error during encryption."); return null; } // at the and of an multi-part operation flags must be reset if (encryptCompleted) encryptInitialized = false; return fileData; } }