KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmanage > core > crypto > KeyManager


1 /**
2  * Copyright 2004-2005 jManage.org
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 package org.jmanage.core.crypto;
17
18 import org.jmanage.core.util.CoreUtils;
19
20 import javax.crypto.SecretKey;
21 import java.io.*;
22
23 /**
24  *
25  * date: Jul 23, 2004
26  * @author Rakesh Kalra
27  */

28 public class KeyManager {
29
30     public static final String JavaDoc KEY_FILE_NAME = "jmanage-key";
31
32     private static final String JavaDoc KEY_FILE_PATH =
33                 CoreUtils.getConfigDir() + File.separatorChar + KEY_FILE_NAME;
34
35     public static void writeKey(EncryptedKey encryptedKey)
36         throws FileNotFoundException, IOException {
37
38         File file = new File(KEY_FILE_PATH);
39         if(file.exists()){
40             file.renameTo(new File(KEY_FILE_PATH + ".bak"));
41         }
42         file.createNewFile();
43
44         FileOutputStream fos = new FileOutputStream(file);
45         fos.write(encryptedKey.get());
46         fos.flush();
47         fos.close();
48     }
49     public static EncryptedKey readKey(char[] password) {
50
51         try {
52             byte[] encryptedKey = readKey();
53             return new EncryptedKey(encryptedKey, password);
54         } catch (IOException e) {
55             throw new RuntimeException JavaDoc(e);
56         }
57     }
58
59     private static byte[] readKey()
60         throws FileNotFoundException, IOException {
61
62         File file = new File(KEY_FILE_PATH);
63         BufferedInputStream is =
64                 new BufferedInputStream(new FileInputStream(file));
65         byte[] encryptedKey = new byte[1000];
66         int data = is.read();
67         int index = 0;
68         while(data != -1){
69             encryptedKey[index] = (byte)data;
70             index ++;
71             data = is.read();
72         }
73         byte[] actualLengthKey = new byte[index];
74         for(int i=0; i<index; i++){
75             actualLengthKey[i] = encryptedKey[i];
76         }
77         is.close();
78         return actualLengthKey;
79     }
80 }
81
Popular Tags