在java中加密和解密属性文件值
我正在寻找一种方法来加密Java程序正在读取的配置文件中的密码。目前,我从文本文件中读入密码,但如果有人查看配置文件,密码就会处于打开状态。
我正在考虑构建一个简单的类,用户可以在其中键入所需的密码,获取密码的加密版本,然后将加密版本粘贴到配置文本文件中。然后,应用程序将读取加密的密码,将密码解密回字符串,然后继续。
我在字符串上遇到了问题 - >crytped字节 - >字符串转换。
我正在使用内置的java安全类来实现此代码。下面是一些示例测试代码:
// Reads password from config file
String password = ScriptConfig.getString( "password" );
// Generate Key
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
// Create Encryption cipher
Cipher cipher = Cipher.getInstance( "DES" );
cipher.init( Cipher.ENCRYPT_MODE, key );
// Encrypt password
byte[] encrypted = cipher.doFinal( password.getBytes() );
// Create decryption cipher
cipher.init( Cipher.DECRYPT_MODE, key );
byte[] decrypted = cipher.doFinal( encrypted );
// Convert byte[] to String
String decryptedString = new String(decrypted);
System.out.println("password: " + password);
System.out.println("encrypted: " + encrypted);
System.out.println("decrypted: " + decryptedString);
// Read encrypted string from config file
String encryptedPassword = ScriptConfig.getString( "encryptedPassword"
);
// Convert encryptedPassword string into byte[]
byte[] encryptedPasswordBytes = new byte[1024];
encryptedPasswordBytes = encryptedPassword.getBytes();
// Decrypt encrypted password from config file
byte[] decryptedPassword = cipher.doFinal( encryptedPasswordBytes );//error here
System.out.println("encryptedPassword: " + encryptedPassword);
System.out.println("decryptedPassword: " + decryptedPassword);
The config file has the following variables:
password=password
encryptedPassword=[B@2a4983
When I run the code, I get the following output:
password: passwd
encrypted: [B@2a4983
decrypted: passwd
javax.crypto.IllegalBlockSizeException: Input length must be multiple
of 8 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
at com.sun.crypto.provider.DESCipher.engineDoFinal(Da shoA12275)
at javax.crypto.Cipher.doFinal(DashoA12275)
at com.sapient.fbi.uid.TestEncryption.main(TestEncryp tion.java:4
有关我用来执行此操作的错误,结构或过程的任何帮助都将很棒。谢谢。