1 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 28 public class KeyManager { 29 30 public static final String KEY_FILE_NAME = "jmanage-key"; 31 32 private static final String 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 (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 |