我有一个程序,它接受用户名和密码并将其存储在文本文件中。在存储密码之前,我加密数据并将密码和生成的加密密钥存储在单独的文本文件中。我有它所以可以制作多个“帐户”,下一个用户信息将在文件的下一行。这工作正常,直到我想从某一行拉出加密的字节密码和密钥,并在使用FileInputStream时解密它。通过搜索存储用户名并记录其存在的行的文本文件,我知道每个密码和密钥属于哪一行。所以我想我的问题是,如何从特定行的文件中提取字节数据以用于解密,并且有更好的方法来进行整个设置。下面是我应该提取字节的代码,使用密钥解密密码,然后验证登录屏幕上输入的密码是否与帐户输入时输入的密码相同。
Login() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
//Check to make sure a username has been entered.
if (!name.contains("[a-zA-Z0-9]") && name.length() > 0 ){
//Find which line the user's data is stored on:
try{
int LineCount = 0;
String line = "";
BufferedReader bReader = new BufferedReader(new FileReader("resources/user_names.txt"));
while ((line = bReader.readLine()) != null) {
LineCount ++;
int posFound = line.indexOf(name);
if (posFound > - 1) {
System.out.println("Search word found at position " + posFound + " on line " + LineCount);
//What do I do here to read my key and password from their text files from the line found above.
//The following code works when there is only one entry on each line of the text files.
FileInputStream keyFis = new FileInputStream("resources/password_keys.txt");
byte[] encKey = new byte[keyFis.available()];
keyFis.read(encKey);
keyFis.close();
Key keyFromFile = new SecretKeySpec(encKey, "DES");
FileInputStream encryptedTextFis = new FileInputStream("resources/user_data.txt");
byte[] encText = new byte[encryptedTextFis.available()];
encryptedTextFis.read(encText);
encryptedTextFis.close();
Cipher decrypter = Cipher.getInstance("DES/ECB/PKCS5Padding");
decrypter.init(Cipher.DECRYPT_MODE, keyFromFile);
byte[] decryptedText = decrypter.doFinal(encText);
System.out.println("Decrypted Text: " + new String(decryptedText));
}else{
JOptionPane.showMessageDialog(null, String.format("The password you entered has not been created."),
"Missing account", JOptionPane.ERROR_MESSAGE);
}
}
bReader.close();
}catch(IOException e){
System.out.println("Error: " + e.toString());
}
}else{
JOptionPane.showMessageDialog(null, String.format("Please enter a valid username."),
"No Input", JOptionPane.ERROR_MESSAGE);
}
}
你可以说我对这种东西很新。我试图使用BufferedReader读取行,但它会将其写入一个字符串,删除我需要用来解密的字节数据。非常感谢任何见解。
答案 0 :(得分:0)
您可以这样做,但是您必须阅读文件中的每一行,直到您感兴趣的行号 - 在Java文件中读取流,因此您必须按顺序浏览它们。这是效率最低的方式。
修改:如果您可以保证每一行都有相同数量的字符,您可以使用skip()
方法执行上述操作,您可以使用{{1}}方法将它的行数乘以每行的字符数,然后到达你想去的地方。
您还可以读取文件一次,并使用列表或地图将其缓存在内存中。这假设您不希望它变大。但是,此时您必须处理保持内存版本和文件版本同步的问题。
真正合适的解决方案是使用LDAP数据库(如LineNumberReader或任何类型的关系数据库)来存储数据 - 假设这对系统架构的其余部分有意义。