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 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 42 public void test(Key encryptKey, Key decryptKey) { 43 Cipher cipher = null; 44 try { 45 cipher = Cipher.getInstance(algorithmName); 46 } catch (NoSuchAlgorithmException e) { 47 Assert.fail(e.getMessage()); 48 } catch (NoSuchPaddingException e) { 49 Assert.fail(e.getMessage()); 50 } 51 try { 52 cipher.init(mode1, encryptKey); 53 } catch (InvalidKeyException e) { 54 Assert.fail(e.getMessage()); 55 } 56 57 byte[] encrypted = crypt(cipher, plainData.getBytes()); 58 59 try { 60 cipher.init(mode2, decryptKey); 61 } catch (InvalidKeyException e) { 62 Assert.fail(e.getMessage()); 63 } 64 65 byte[] decrypted = crypt(cipher, encrypted); 66 67 String decryptedString = new String(decrypted); 68 69 Assert.assertEquals("transformed data does not match", plainData, 70 decryptedString); 71 } 72 73 public byte[] crypt(Cipher cipher, byte[] input) { 74 try { 75 return cipher.doFinal(input); 76 } catch (IllegalBlockSizeException e) { 77 Assert.fail(e.getMessage()); 78 } catch (BadPaddingException e) { 79 Assert.fail(e.getMessage()); 80 } 81 return null; 82 } 83 } 84