我有一个程序,它接受用户名和密码并将其存储在文本文件中。在存储密码之前,我加密数据并将密码和生成的加密密钥存储在单独的文本文件中。我拥有它,因此可以创建多个“帐户”,并且下一个用户信息位于文件的下一行。这工作正常,直到我想从某一行提取加密的字节密码和密钥并在使用 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 读取这些行,但它会将其写入一个字符串,该字符串会删除我需要用来解密的字节数据。非常感谢任何见解。