1 /* 2 * Copyright (C) 2009 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 */ 16 17 package tests.security; 18 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; 27 28 public abstract class CipherHelper<T> extends TestHelper<T> { 29 30 private final String algorithmName; 31 private final String plainData; 32 private final int mode1; 33 private final int mode2; 34 CipherHelper(String algorithmName, String plainData, int mode1, int mode2)35 public CipherHelper(String algorithmName, String plainData, int mode1, int mode2) { 36 this.algorithmName = algorithmName; 37 this.plainData = plainData; 38 this.mode1 = mode1; 39 this.mode2 = mode2; 40 } 41 test(Key encryptKey, Key decryptKey)42 public void test(Key encryptKey, Key decryptKey) throws Exception { 43 Cipher cipher = Cipher.getInstance(algorithmName); 44 cipher.init(mode1, encryptKey); 45 byte[] encrypted = cipher.doFinal(plainData.getBytes()); 46 47 cipher.init(mode2, decryptKey); 48 byte[] decrypted = cipher.doFinal(encrypted); 49 String decryptedString = new String(decrypted); 50 51 Assert.assertEquals("transformed data does not match", plainData, decryptedString); 52 } 53 } 54