1/*
2 * Copyright (C) 2008 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 */
16package org.apache.harmony.crypto.tests.javax.crypto.func;
17
18
19import java.security.Key;
20import java.security.NoSuchAlgorithmException;
21import java.security.SecureRandom;
22
23import javax.crypto.KeyGenerator;
24
25public class KeyGeneratorThread extends TestThread {
26    KeyGeneratorThread(String[] names) {
27        super(names);
28    }
29
30    public void test() throws Exception {
31        KeyGenerator kg = KeyGenerator.getInstance(algName);
32        Key k = kg.generateKey();
33        if(kg.getAlgorithm().toLowerCase().equals(k.getAlgorithm().toLowerCase()) != true) {
34            throw new Exception ("Algorithm names not matched for KeyGenerator" +
35                    " and for Key objects");
36        }
37        if(kg.getAlgorithm().toLowerCase().equals(algName.toLowerCase()) != true) {
38            throw new Exception ("Algorithm names not matched for KeyGenerator" +
39            " and for Key objects");
40        }
41        byte[] array1 = k.getEncoded();
42        k = kg.generateKey();
43        byte[] array2 = k.getEncoded();
44        int matches = 0;
45        for (int i = 0; i < array1.length; i++) {
46            if (array1[i] == array2[i]) {
47                matches++;
48            }
49        }
50        if (matches > array1.length / 2) {
51            throw new Exception("Generated keys are simular");
52        }
53        SecureRandom random = new SecureRandom();
54        kg.init(random);
55        matches = 0;
56        k = kg.generateKey();
57        array1 = k.getEncoded();
58        random = new SecureRandom();
59        kg.init(random);
60        k = kg.generateKey();
61        array2 = k.getEncoded();
62        for (int i = 0; i < array1.length; i++) {
63            if (array1[i] == array2[i]) {
64                matches++;
65            }
66        }
67    }
68}
69