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 decryptInitialized = false; /** * Cipherobject to make decrypt operations */ private static Cipher decryptCipher; /** * This method should be used to decrypt a block of data. * * @param fileData the data to decrypt. * @param decryptionKey the key to initialize the cipher-algorithm. * @param decryptCompleted a flag, that indicates, that a multi-part decryption 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 decrypted in one operation. * * @return the decrypted data. */ public static byte[] decryptData(byte[] fileData, byte[] decryptionKey, boolean decryptCompleted) { // 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 (!decryptInitialized) { // Initializing the cipher try { decryptCipher = Cipher.getInstance("AES"); } catch (Exception e) { e.printStackTrace(); return null; } try { SecretKeySpec keySpec = new SecretKeySpec(decryptionKey, "AES"); decryptCipher.init(Cipher.DECRYPT_MODE, keySpec); } catch (Exception e) { Log.e(TAG, "Error while initializing decryption."); return null; } decryptInitialized = true; } // Decrypting try { if (!decryptCompleted) // done in case of multi-part operation fileData = decryptCipher.update(fileData); else // done in case of single part operation or to finish a // multi-part operation fileData = decryptCipher.doFinal(fileData); } catch (Exception e) { Log.e(TAG, "Error during decryption."); return null; } // at the and of an multi-part operation flags must be reset if (decryptCompleted) decryptInitialized = false; return fileData; } }