2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package tests.security;
19 import java.security.InvalidKeyException;
20 import java.security.Key;
21 import java.security.NoSuchAlgorithmException;
22 import javax.crypto.BadPaddingException;
23 import javax.crypto.Cipher;
24 import javax.crypto.IllegalBlockSizeException;
25 import javax.crypto.NoSuchPaddingException;
26 import junit.framework.Assert;
28 public abstract class CipherHelper<T> extends TestHelper<T> {
30 private final String algorithmName;
31 private final String plainData;
32 private final int mode1;
33 private final int mode2;
35 public CipherHelper(String algorithmName, String plainData, int mode1, int mode2) {
36 this.algorithmName = algorithmName;
37 this.plainData = plainData;
42 public void test(Key encryptKey, Key decryptKey) {
45 cipher = Cipher.getInstance(algorithmName);
46 } catch (NoSuchAlgorithmException e) {
47 Assert.fail(e.getMessage());
48 } catch (NoSuchPaddingException e) {
49 Assert.fail(e.getMessage());
52 cipher.init(mode1, encryptKey);
53 } catch (InvalidKeyException e) {
54 Assert.fail(e.getMessage());
57 byte[] encrypted = crypt(cipher, plainData.getBytes());
60 cipher.init(mode2, decryptKey);
61 } catch (InvalidKeyException e) {
62 Assert.fail(e.getMessage());
65 byte[] decrypted = crypt(cipher, encrypted);
67 String decryptedString = new String(decrypted);
69 Assert.assertEquals("transformed data does not match", plainData,
73 public byte[] crypt(Cipher cipher, byte[] input) {
75 return cipher.doFinal(input);
76 } catch (IllegalBlockSizeException e) {
77 Assert.fail(e.getMessage());
78 } catch (BadPaddingException e) {
79 Assert.fail(e.getMessage());