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 17package tests.security; 18 19import java.security.AlgorithmParameters; 20import java.security.InvalidAlgorithmParameterException; 21import java.security.InvalidKeyException; 22import java.security.Key; 23import java.security.NoSuchAlgorithmException; 24import java.util.Arrays; 25import javax.crypto.BadPaddingException; 26import javax.crypto.Cipher; 27import javax.crypto.IllegalBlockSizeException; 28import javax.crypto.KeyGenerator; 29import javax.crypto.NoSuchPaddingException; 30import junit.framework.Assert; 31 32public class AlgorithmParameterSymmetricHelper extends TestHelper<AlgorithmParameters> { 33 34 private static final String plainData = "some data to encrypt and decrypt"; 35 private final String algorithmName; 36 private final int keySize; 37 private String blockmode; 38 39 public AlgorithmParameterSymmetricHelper(String algorithmName, int keySize) { 40 this.algorithmName = algorithmName; 41 this.keySize = keySize; 42 } 43 44 public AlgorithmParameterSymmetricHelper(String algorithmName, String blockmode, int keySize) { 45 this(algorithmName, keySize); 46 this.blockmode = blockmode; 47 } 48 49 @Override 50 public void test(AlgorithmParameters parameters) throws Exception { 51 KeyGenerator generator = KeyGenerator.getInstance(algorithmName); 52 generator.init(keySize); 53 54 Key key = generator.generateKey(); 55 String transformation = algorithmName; 56 if (blockmode != null) 57 { 58 transformation += "/" + blockmode; 59 } 60 61 Cipher cipher = Cipher.getInstance(transformation); 62 cipher.init(Cipher.ENCRYPT_MODE, key, parameters); 63 byte[] bs = cipher.doFinal(plainData.getBytes()); 64 65 cipher.init(Cipher.DECRYPT_MODE, key, parameters); 66 byte[] decrypted = cipher.doFinal(bs); 67 68 Assert.assertTrue(Arrays.equals(plainData.getBytes(), decrypted)); 69 } 70} 71