CipherSymmetricKeyThread.java revision cc05ad238516f1303687aba4a978e24e57c0c07a
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package org.apache.harmony.crypto.tests.javax.crypto.func; 17 18 19import java.security.Key; 20import java.security.NoSuchAlgorithmException; 21import java.security.SecureRandom; 22 23import javax.crypto.Cipher; 24import javax.crypto.KeyGenerator; 25import javax.crypto.spec.IvParameterSpec; 26 27public class CipherSymmetricKeyThread extends CipherThread { 28 CipherSymmetricKeyThread(String name, int[] keys, String[] modes, String[] paddings) { 29 super(name, keys, modes, paddings); 30 } 31 32 33 @Override 34 public void crypt() throws Exception { 35 byte[] output = new byte[128]; 36 byte[] decrypted = new byte[128]; 37 byte[] input = getData().getBytes(); 38 SecureRandom sr = new SecureRandom(); 39 byte[] iv = null;//new byte[16]; 40 int outputSize = 0; 41 42 KeyGenerator kg = KeyGenerator.getInstance(getAlgName()); 43 kg.init(getKeyLength(), new SecureRandom()); 44 Key key = kg.generateKey(); 45 46 Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + 47 getPadding()); 48 if (getAlgName() != "AES") { 49 iv = new byte[8]; 50 } else { 51 iv = new byte[16]; 52 } 53 sr.nextBytes(iv); 54 IvParameterSpec ivspec = new IvParameterSpec(iv); 55 if (getMode() != "ECB") { 56 cip.init(Cipher.ENCRYPT_MODE, key, ivspec); 57 cip.doFinal(input, 0, input.length, output); 58 outputSize = cip.getOutputSize(input.length); 59 iv = cip.getIV(); 60 ivspec = new IvParameterSpec(iv); 61 cip.init(Cipher.DECRYPT_MODE, key, ivspec); 62 cip.doFinal(output, 0, outputSize, decrypted); 63 } else { 64 cip.init(Cipher.ENCRYPT_MODE, key); 65 cip.doFinal(input, 0, input.length, output); 66 outputSize = cip.getOutputSize(input.length); 67 cip.init(Cipher.DECRYPT_MODE, key); 68 cip.doFinal(output, 0, outputSize, decrypted); 69 } 70 71 checkEncodedData(getData().getBytes(), decrypted); 72 } 73} 74