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.SecureRandom;
20import java.security.spec.AlgorithmParameterSpec;
21
22import javax.crypto.Cipher;
23import javax.crypto.SecretKey;
24import javax.crypto.SecretKeyFactory;
25import javax.crypto.spec.PBEKeySpec;
26import javax.crypto.spec.PBEParameterSpec;
27
28public class CipherPBEThread extends CipherThread {
29
30    CipherPBEThread(String name, int[] keys, String[] modes, String[] paddings) {
31        super(name, keys, modes, paddings);
32    }
33
34    @Override
35    public void crypt() throws Exception {
36        byte[] output = new byte[128];
37        byte[] decrypted = new byte[128];
38        byte[] input  =  getData().getBytes();
39        byte[] salt = new byte[8];
40        SecureRandom sr = new SecureRandom();
41
42        PBEKeySpec keySpec = new PBEKeySpec("top sicret password".toCharArray());
43        SecretKeyFactory skf = SecretKeyFactory.getInstance(getAlgName());
44        SecretKey key = skf.generateSecret(keySpec);
45
46        Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" +
47                getPadding());
48
49        sr.nextBytes(salt);
50        PBEParameterSpec parSpec = new PBEParameterSpec(salt, getKeyLength());
51
52        cip.init(Cipher.ENCRYPT_MODE, key, parSpec);
53        cip.doFinal(input, 0, input.length, output);
54        int outputSize = cip.getOutputSize(input.length);
55        cip.init(Cipher.DECRYPT_MODE, key, parSpec);
56        cip.doFinal(output, 0, outputSize, decrypted);
57
58        checkEncodedData(getData().getBytes(), decrypted);
59    }
60}
61