下面是一个进行加密的工具类,加密类会产生一个密钥文件,密钥文件保存到了硬盘文件中,程序中要进行对数据的加解密操作。密钥文件保存在文件,别人也就可以读取密钥文件,获得加密数据的内容。有什么可以安全保存密钥文件的方式么?
public class EncryptUtil {
private static String keyPath = null; private static String getKeyPath() {
keyPath = "c:\\yhb.des";
return keyPath;
}

/**
 * 对称加密-产生密钥<br/>
 */
public static void generatorKey() {
SecretKey key = null;
try {
// 指定算法,这里为DES;如果想用Blowfish算法,则用getInstance("Blowfish")
// BouncyCastle基本上支持所有通用标准算法
KeyGenerator keygen = KeyGenerator.getInstance("DES");
// 指定密钥长度,长度越高,加密强度越大
keygen.init(56);
// 产生密钥
key = keygen.generateKey();
// 构造输出文件,这里的目录是动态的,根据用户名称来构造目录
ObjectOutputStream keyFile = new ObjectOutputStream(
new FileOutputStream(getKeyPath()));
keyFile.writeObject(key);
keyFile.close();
} catch (NoSuchAlgorithmException e5) {
e5.printStackTrace(); System.exit(0);
} catch (IOException e4) {
e4.printStackTrace(); System.exit(0);
}
}

/**
 * 对称加密-读取密钥.<br/>
 */
private static SecretKey getSecretKey() {
// 从密钥文件中读密钥
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
new FileInputStream(getKeyPath()));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
e1.printStackTrace(); System.exit(0);
} catch (Exception ey2) {
e2.printStackTrace(); }
return key;
} /**
 * 加密文本信息.<br/>
 */
public static String encrypt(String encryptStr) {
SecretKey key = getSecretKey();
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
ey3.printStackTrace();
}
byte[] data = null;
try {
data = cipher.doFinal(encryptStr.getBytes());
} catch (IllegalBlockSizeException e) {
e.printStackTrace(); } catch (BadPaddingException e) {
e.printStackTrace(); }
encryptStr = Base64.encodeBase64String(data);
return encryptStr;
}

/**
 * 解密文本信息.<br/>
 */
public static String decrypt(String decryptStr) {
SecretKey key = getSecretKey();
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ey3) {
ey3.printStackTrace(); System.exit(0);
}
byte[] data = Base64.decodeBase64(decryptStr);
try {
data = cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
e.printStackTrace(); } catch (BadPaddingException e) {
e.printStackTrace(); }
decryptStr = new String(data);
return decryptStr;
}
}