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.AlgorithmParameters;
20 import java.security.InvalidAlgorithmParameterException;
21 import java.security.InvalidKeyException;
22 import java.security.KeyPair;
23 import java.security.KeyPairGenerator;
24 import java.security.NoSuchAlgorithmException;
25 import java.util.Arrays;
26 import javax.crypto.BadPaddingException;
27 import javax.crypto.Cipher;
28 import javax.crypto.IllegalBlockSizeException;
29 import javax.crypto.NoSuchPaddingException;
30 import junit.framework.Assert;
31 
32 public class AlgorithmParameterAsymmetricHelper extends TestHelper<AlgorithmParameters> {
33 
34     private static final String plainData = "some data to encrypt and decrypt";
35     private final String algorithmName;
36 
AlgorithmParameterAsymmetricHelper(String algorithmName)37     public AlgorithmParameterAsymmetricHelper(String algorithmName) {
38         this.algorithmName = algorithmName;
39     }
40 
41     @Override
test(AlgorithmParameters parameters)42     public void test(AlgorithmParameters parameters) throws Exception {
43         KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithmName);
44         generator.initialize(1024);
45         KeyPair keyPair = generator.generateKeyPair();
46 
47         Cipher cipher = Cipher.getInstance(algorithmName);
48         cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), parameters);
49         byte[] bs = cipher.doFinal(plainData.getBytes());
50 
51         cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate(), parameters);
52         byte[] decrypted = cipher.doFinal(bs);
53         Assert.assertTrue(Arrays.equals(plainData.getBytes(), decrypted));
54     }
55 }
56