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.InvalidKeyException;
21import java.security.KeyPair;
22import java.security.KeyPairGenerator;
23import java.security.NoSuchAlgorithmException;
24import javax.crypto.KeyAgreement;
25import junit.framework.Assert;
26
27public class AlgorithmParameterKeyAgreementHelper extends TestHelper<AlgorithmParameters> {
28
29    private final String algorithmName;
30
31    public AlgorithmParameterKeyAgreementHelper(String algorithmName) {
32        this.algorithmName = algorithmName;
33    }
34
35    @Override
36    public void test(AlgorithmParameters parameters) {
37
38        KeyPairGenerator generator = null;
39        try {
40            generator = KeyPairGenerator.getInstance(algorithmName);
41        } catch (NoSuchAlgorithmException e) {
42            Assert.fail(e.getMessage());
43        }
44
45        generator.initialize(1024);
46
47        KeyPair keyPair = generator.generateKeyPair();
48
49        KeyAgreement keyAgreement = null;
50        try {
51            keyAgreement = KeyAgreement.getInstance(algorithmName);
52        } catch (NoSuchAlgorithmException e) {
53            Assert.fail(e.getMessage());
54        }
55
56        try {
57            keyAgreement.init(keyPair.getPrivate());
58        } catch (InvalidKeyException e) {
59            Assert.fail(e.getMessage());
60        }
61        try {
62            keyAgreement.doPhase(keyPair.getPublic(), true);
63        } catch (InvalidKeyException e) {
64            Assert.fail(e.getMessage());
65        } catch (IllegalStateException e) {
66            Assert.fail(e.getMessage());
67        }
68        Assert.assertNotNull("generated secret is null", keyAgreement
69                .generateSecret());
70    }
71}
72