Guest User

Untitled

a guest
Jul 10th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.47 KB | None | 0 0
  1. package com.speljohan.rsbot.gui;
  2.  
  3. import java.awt.Component;
  4. import java.awt.GridBagConstraints;
  5. import java.awt.GridBagLayout;
  6. import java.awt.Insets;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseListener;
  11. import java.io.BufferedReader;
  12. import java.io.BufferedWriter;
  13. import java.io.File;
  14. import java.io.FileNotFoundException;
  15. import java.io.FileReader;
  16. import java.io.FileWriter;
  17. import java.io.IOException;
  18. import java.io.UnsupportedEncodingException;
  19. import java.security.MessageDigest;
  20. import java.security.NoSuchAlgorithmException;
  21. import java.util.Map;
  22. import java.util.TreeMap;
  23.  
  24. import javax.naming.NamingException;
  25. import javax.swing.JButton;
  26. import javax.swing.JCheckBox;
  27. import javax.swing.JFrame;
  28. import javax.swing.JLabel;
  29. import javax.swing.JList;
  30. import javax.swing.JOptionPane;
  31. import javax.swing.JPanel;
  32. import javax.swing.JPasswordField;
  33. import javax.swing.JScrollPane;
  34. import javax.swing.JSpinner;
  35. import javax.swing.JTextField;
  36. import javax.swing.ListSelectionModel;
  37. import javax.swing.SpinnerNumberModel;
  38.  
  39. import com.speljohan.rsbot.util.GlobalConfiguration;
  40.  
  41. /**
  42. * This will handle the management of Accounts for the Bot.<br>
  43. * Information will be stored in a file specified by fileName.<br>
  44. * Format for accounts should be:<br>
  45. * &nbsp;&nbsp; Name:Password[:Pin] <br>
  46. * Pin may be omitted if no Pin on Account
  47. *
  48. * @author Fusion89k
  49. */
  50. // The brackets [] are there to denote optional.
  51. public class AccountManager extends JFrame implements ActionListener {
  52. private static final long serialVersionUID = 6401178388485322197L;
  53. private JList names;
  54. private GridBagConstraints c;
  55. public final static String sepChar = ":",
  56. fileName = GlobalConfiguration.Paths.getAccountsFile();
  57. private final String emptyName = "No Accounts Found";
  58. static String key;
  59. private static Map<String, String> accounts;
  60.  
  61. public AccountManager() {
  62. if (accounts.size() < 1)
  63. accounts.put(emptyName, "");
  64. createAndDisplayGUI();
  65. }
  66.  
  67. /**
  68. * Access the password of the given account
  69. *
  70. * @param name
  71. * Name of account to access password of
  72. * @return Unencrypted Password
  73. */
  74. public static String getPassword(String name) {
  75. String password = accounts.get(name);
  76. if (password != null && password.contains(sepChar))
  77. password = password.split(sepChar, 2)[0];
  78. return crypt(password, false);
  79. }
  80.  
  81. /**
  82. * Access the pin for the given account
  83. *
  84. * @param name
  85. * Name of the account
  86. * @return Pin or -1 if no pin
  87. */
  88. public static String getPin(String name) {
  89. String all = accounts.get(name);
  90. if (all.contains(sepChar))
  91. return all.split(sepChar, 2)[1];
  92. return "-1";
  93. }
  94.  
  95. /**
  96. * Access the list of names for loaded accounts
  97. *
  98. * @return Array of the Names
  99. */
  100. public static String[] getAccountNames() {
  101. return accounts.keySet().toArray(new String[0]);
  102. }
  103.  
  104. /**
  105. * Allows addition of an account
  106. *
  107. * @param info
  108. * Account info in format of name:pass[:pin]
  109. */
  110. public static void addAccount(String info) throws NamingException {
  111. if (!info.contains(sepChar))
  112. throw new NamingException(info + " is not in the correct format.");
  113. String[] parts = info.split(sepChar);
  114. accounts.put(fixName(parts[0]), crypt(parts[1], true));
  115. if (parts.length > 2)
  116. accounts.put(fixName(parts[0]), crypt(parts[1], true) + sepChar
  117. + parts[2]);
  118. saveAccounts();
  119. }
  120.  
  121. /**
  122. * Creates and Displays the main GUI
  123. *
  124. * This GUI has the list and the main buttons
  125. */
  126. private void createAndDisplayGUI() {
  127. c = new GridBagConstraints();
  128. // Main Panel with everything
  129. JPanel pane = new JPanel(new GridBagLayout());
  130. // Makes the List
  131. names = new JList(accounts.keySet().toArray(new String[0]));
  132. // Only one selection at a time
  133. names.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  134. // Will display the password and pin when double clicked or right
  135. // clicked
  136. names.addMouseListener(new MouseListener() {
  137. public void mouseClicked(MouseEvent click) {
  138. if (click.getClickCount() > 1
  139. || click.getButton() == MouseEvent.BUTTON3) {
  140. String clicked = accounts
  141. .get(((JList) click.getComponent())
  142. .getSelectedValue());
  143. if (clicked.isEmpty())
  144. return;
  145. String pass = clicked.contains(sepChar) ? clicked
  146. .substring(0, clicked.indexOf(sepChar)) : clicked;
  147. pass = crypt(pass, false);
  148. String info = "Password: " + pass;
  149. if (clicked.contains(sepChar)) {
  150. info += "\nPin: "
  151. + clicked.substring(
  152. clicked.indexOf(sepChar) + 1, clicked
  153. .length());
  154. }
  155. JOptionPane.showMessageDialog(null, info);
  156. }
  157. }
  158.  
  159. public void mouseEntered(MouseEvent click) {
  160. }
  161.  
  162. public void mouseExited(MouseEvent click) {
  163. }
  164.  
  165. public void mousePressed(MouseEvent click) {
  166. }
  167.  
  168. public void mouseReleased(MouseEvent click) {
  169. }
  170. });
  171.  
  172. // Enables scrolling through the List
  173. JScrollPane scroll = new JScrollPane(names);
  174.  
  175. JButton add = new JButton("Add Account");// Button 1
  176. JButton del = new JButton("Delete Account");// Button 2
  177. JButton save = new JButton("Save Accounts");// Button 3
  178.  
  179. add.addActionListener(this);
  180. del.addActionListener(this);
  181. save.addActionListener(this);
  182. // Positions Everything Correctly on the panel
  183. c.gridy = 0;
  184. c.gridwidth = GridBagConstraints.REMAINDER;
  185. c.fill = GridBagConstraints.BOTH;
  186. pane.add(scroll, c);
  187. c.gridwidth = 1;
  188. c.gridy = 1;
  189. c.gridx = 0;
  190. c.fill = GridBagConstraints.NONE;
  191. c.insets = new Insets(5, 5, 0, 5);
  192. c.anchor = GridBagConstraints.CENTER;
  193. pane.add(add, c);
  194. c.gridx = GridBagConstraints.RELATIVE;
  195. pane.add(del, c);
  196. pane.add(save, c);
  197. names.setSelectedIndex(0);
  198. add(pane);
  199. pack();
  200. setLocationRelativeTo(getOwner());
  201. setVisible(true);
  202. setResizable(false);
  203. setTitle("Account Manager");
  204. }
  205.  
  206. /**
  207. * Controls all of the button and checkBox actions of the program
  208. */
  209. public void actionPerformed(ActionEvent event) {
  210. JFrame parentFrame;
  211. Component comp = ((Component) event.getSource()).getParent();
  212. while (!(comp instanceof JFrame))
  213. comp = comp.getParent();
  214. parentFrame = (JFrame) comp;
  215. if (event.getSource() instanceof JButton) {
  216. switch (((JButton) event.getSource()).getText().charAt(0)) {
  217. case 'A':// Add Accounts
  218. if (event.getActionCommand().contains("dd"))
  219. addAccount();
  220. else {// Update the List with the new Account
  221. JPanel pane = (JPanel) ((JButton) event.getSource())
  222. .getParent();
  223. String name = null, pass = null, pin = "";
  224. for (Component c : pane.getComponents()) {
  225. if (c instanceof JPasswordField)
  226. pass = ((JTextField) c).getText();
  227. else if (c instanceof JTextField)
  228. name = ((JTextField) c).getText();
  229. else if (c instanceof JSpinner)
  230. pin += ((JSpinner) c).getValue();
  231. }
  232. if (name.isEmpty() || pass.isEmpty()) {
  233. JOptionPane.showMessageDialog(null, "Empty Fields");
  234. return;
  235. }
  236. accounts.put(fixName(name), crypt(pass, true)
  237. + (pin.isEmpty() ? "" : sepChar + pin));
  238. refreshList();
  239. names.validate();
  240. parentFrame.dispose();
  241. }
  242. break;
  243. case 'D':// Delete Accounts
  244. if (accounts.get(names.getSelectedValue()).isEmpty())
  245. return;
  246. int yes = JOptionPane.showConfirmDialog(this,
  247. "Are you sure you want to delete "
  248. + names.getSelectedValue() + "?", "Delete",
  249. JOptionPane.YES_NO_OPTION);
  250. if (yes == 0) {
  251. accounts.remove(names.getSelectedValue());
  252. refreshList();
  253. names.validate();
  254. }
  255. break;
  256. case 'S':// Save Accounts
  257. saveAccounts();
  258. break;
  259. }
  260. } else if (event.getSource() instanceof JCheckBox) {
  261. // CheckBox for Pins add and remove JSpinners
  262. JCheckBox jcb = ((JCheckBox) event.getSource());
  263. if (jcb.isSelected()) {
  264. // Add Spinners
  265. c = new GridBagConstraints();
  266. c.gridy = 2;
  267. c.gridx = 1;
  268. c.weightx = 1;
  269. c.insets = new Insets(0, 0, 5, 5);
  270. JSpinner[] spins = new JSpinner[4];
  271. for (int i = 0; i < spins.length; i++) {
  272. spins[i] = new JSpinner(new SpinnerNumberModel(0, 0, 9, 1));
  273. jcb.getParent().add(spins[i], c);
  274. c.gridx = GridBagConstraints.RELATIVE;
  275. }
  276. parentFrame.pack();
  277. } else {
  278. // Remove Spinners
  279. for (Component c : jcb.getParent().getComponents())
  280. if (c instanceof JSpinner)
  281. jcb.getParent().remove(c);
  282. parentFrame.validate();
  283. }
  284. }
  285. }
  286.  
  287. /**
  288. * Gets the necessary information from the user to make a new account
  289. */
  290. private void addAccount() {
  291. JFrame addFrame = new JFrame("Add Account");
  292. JPanel pane = new JPanel(new GridBagLayout());
  293. c = new GridBagConstraints();
  294. JTextField userName = new JTextField(8);
  295. JPasswordField userPass = new JPasswordField(8);
  296. userPass.setEchoChar('*');
  297. c.gridwidth = 2;
  298. c.fill = GridBagConstraints.HORIZONTAL;
  299. c.insets = new Insets(5, 5, 0, 7);
  300. pane.add(new JLabel("User Name: ", JLabel.CENTER), c);
  301. c.gridx = GridBagConstraints.RELATIVE;
  302. c.gridwidth = 3;
  303. c.insets = new Insets(5, 0, 0, 5);
  304. pane.add(userName, c);
  305. c.insets = new Insets(5, 5, 5, 7);
  306. c.gridwidth = 2;
  307. c.gridx = 0;
  308. c.gridy = 1;
  309. pane.add(new JLabel("Password: ", JLabel.CENTER), c);
  310. c.insets = new Insets(5, 0, 5, 5);
  311. c.gridwidth = 3;
  312. c.gridx = GridBagConstraints.RELATIVE;
  313. pane.add(userPass, c);
  314. JCheckBox pinCheck = new JCheckBox("Pin");
  315. pinCheck.addActionListener(this);
  316. c = new GridBagConstraints();
  317. c.gridy = 2;
  318. c.insets = new Insets(0, 5, 5, 5);
  319. pane.add(pinCheck, c);
  320.  
  321. JButton save = new JButton("Add Account");
  322. save.setActionCommand("Update");
  323. save.addActionListener(this);
  324. c.gridy = 3;
  325. c.gridwidth = GridBagConstraints.REMAINDER;
  326. pane.add(save, c);
  327.  
  328. addFrame.add(pane);
  329. addFrame.pack();
  330. addFrame.setLocationRelativeTo(this);
  331. addFrame.setVisible(true);
  332. }
  333.  
  334. /**
  335. * Resets the Model for the List to reflect changes made to the accounts Map
  336. */
  337. private void refreshList() {
  338. if (accounts.keySet().size() > 1
  339. && accounts.keySet().contains(emptyName))
  340. accounts.remove(emptyName);
  341. else if (accounts.keySet().size() < 1)
  342. accounts.put(emptyName, "");
  343. names.setListData(accounts.keySet().toArray(new String[0]));
  344. names.getParent().validate();
  345. }
  346.  
  347. /**
  348. * Capitalizes the first character and replaces spaces with underscores
  349. * Purely esthetic
  350. *
  351. * @param name
  352. * Name to fix
  353. * @return Fixed name
  354. */
  355. private static String fixName(String name) {
  356. if (name.charAt(0) > 91)
  357. name = ((char) ((int) name.charAt(0) - 32)) + name.substring(1);
  358. while (name.contains(" "))
  359. name = name.substring(0, name.indexOf(" ")) + "_"
  360. + name.substring(name.indexOf(" ") + 1);
  361. return name;
  362. }
  363.  
  364. /**
  365. * Encrypts/Decrypts a string using a SHA1 hash of (String) key from other
  366. * users computers
  367. *
  368. * @author Jacmob
  369. */
  370. private static String crypt(String start, boolean en) {
  371. String delim = "a";
  372. if (start == null)
  373. return null;
  374. byte[] hashedkey;
  375. byte[] password;
  376. int i;
  377. try {
  378. hashedkey = SHA1(key);
  379. } catch (NoSuchAlgorithmException e) {
  380. e.printStackTrace();
  381. return start;
  382. } catch (UnsupportedEncodingException e) {
  383. e.printStackTrace();
  384. return start;
  385. }
  386. if (en) {
  387. String end = "";
  388. password = start.getBytes();
  389. for (i = 0; i < hashedkey.length; i ++) {
  390. if (i < start.length()) {
  391. end += (hashedkey[i] + password[i]) + delim;
  392. } else {
  393. end += hashedkey[i] + delim;
  394. }
  395. }
  396. return end.substring(0, end.length() - delim.length());
  397. } else {
  398. String[] temp = start.split(delim);
  399. password = new byte[temp.length];
  400. for (i = 0; i < hashedkey.length; i ++) {
  401. int temp2 = Integer.parseInt(temp[i]);
  402. if (hashedkey[i] == temp2)
  403. break;
  404. else
  405. password[i] = (byte)(temp2 - hashedkey[i]);
  406. }
  407. return new String(password, 0, i);
  408. }
  409. }
  410.  
  411. /**
  412. * Returns SHA1 hash of a String.
  413. */
  414. private static byte[] SHA1(String in) throws NoSuchAlgorithmException,
  415. UnsupportedEncodingException {
  416. MessageDigest md;
  417. md = MessageDigest.getInstance("SHA-1");
  418. byte[] sha1hash = new byte[40];
  419. md.update(in.getBytes("iso-8859-1"), 0, in.length());
  420. sha1hash = md.digest();
  421. return sha1hash;
  422. }
  423.  
  424. /**
  425. * Loads the accounts from the file
  426. */
  427. private static Map<String, String> loadAccounts() throws NamingException {
  428. TreeMap<String, String> accounts = new TreeMap<String, String>();
  429. File accountFile = new File(fileName);
  430. if (accountFile.exists()) {
  431. try {
  432. BufferedReader in = new BufferedReader(new FileReader(
  433. accountFile));
  434. String temp;// Used to store the lines from the file
  435. while ((temp = in.readLine()) != null) {
  436. if (temp.isEmpty())
  437. continue;
  438. // Means that it is in old format
  439. if (temp.contains("USERNAME"))
  440. return fixAccounts();
  441. // If for some reason the format is not as expected
  442. if (!temp.contains(sepChar))
  443. throw new NamingException("Invliad Storage of: " + temp);
  444. String[] parts = temp.split(sepChar, 2);
  445. for (String s : parts)
  446. if (s.isEmpty())
  447. throw new NamingException("Invliad Storage of: "
  448. + temp);
  449. // Formats the name
  450. parts[0] = fixName(parts[0]);
  451. // Checks Pin Validity
  452. try {
  453. if (parts.length > 2
  454. && (parts[2].length() != 4 || Integer
  455. .parseInt(parts[2]) >= 0))
  456. throw new NamingException("Invalid Pin: "
  457. + parts[2] + " On Account: " + parts[0]);
  458. } catch (NumberFormatException e) {
  459. throw new NamingException("Invalid Pin: " + parts[2]
  460. + " On Account: " + parts[0]);
  461. }
  462. System.out
  463. .println("Loaded: " + parts[0] + " | " + parts[1]);
  464. accounts.put(parts[0], parts[1]);
  465. }
  466. in.close();
  467. } catch (FileNotFoundException e) {// From File Loading
  468. e.printStackTrace();
  469. } catch (IOException e) {// From Reader traversal
  470. e.printStackTrace();
  471. }
  472. }
  473. return accounts;
  474. }
  475.  
  476. /**
  477. * Will convert account files from the old format to the new format
  478. *
  479. * Old Format - key=value, key=value,[key=value,]
  480. *
  481. * New Format - name:pass[:pin]
  482. *
  483. * @return A mapping of name password/pin pairs
  484. */
  485. private static Map<String, String> fixAccounts() throws NamingException {
  486. String endResult = "";
  487. try {
  488. BufferedReader in = new BufferedReader(new FileReader(fileName));
  489. String temp;
  490. while ((temp = in.readLine()) != null) {
  491. if (temp.contains("USERNAME")) {
  492. String pass = null, name = null, pin = null;
  493. // Old Format key=value,
  494. for (String part : temp.split(",")) {
  495. // Splits Keys and Values
  496. String[] pieces = part.split("=", 2);
  497. if (pieces[0].equals("PASSWORD"))// Key
  498. pass = crypt(pieces[1], true);
  499. else if (pieces[0].equals("USERNAME"))// Key
  500. name = pieces[1];
  501. else if (pieces[0].equals("PIN"))// Key
  502. pin = pieces[1];
  503. }
  504. try {
  505. // Converts to new format name:pass[:pin]
  506. endResult += name + sepChar + pass
  507. + (pin != null ? (sepChar + pin) : "");
  508. } catch (NullPointerException e) {
  509. // Will only happen if one of the keys is not found
  510. System.out.println("File Already Fixed");
  511. try {
  512. return loadAccounts();
  513. } catch (NamingException e1) {
  514. e1.printStackTrace();
  515. }
  516. }
  517. endResult += System.getProperty("line.separator");
  518. }
  519. }
  520. in.close();
  521. // Writes the new format to the file
  522. BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
  523. out.append(endResult);
  524. out.close();
  525. } catch (FileNotFoundException e) {
  526. e.printStackTrace();
  527. } catch (IOException e) {
  528. e.printStackTrace();
  529. }
  530. // Reload the accounts
  531. return loadAccounts();
  532. }
  533.  
  534. /**
  535. * Writes the accounts to the file
  536. */
  537. private static void saveAccounts() {
  538. File accountFile = new File(fileName);
  539. try {
  540. BufferedWriter out = new BufferedWriter(new FileWriter(accountFile));
  541. for (String s : accounts.keySet()) {
  542. if (accounts.get(s).isEmpty())
  543. continue;
  544. out.append(s + sepChar + accounts.get(s));
  545. out.newLine();
  546. }
  547. out.close();
  548. } catch (IOException e) {
  549. e.printStackTrace();
  550. }
  551. }
  552.  
  553. static {
  554. key = System.getProperty("user.name").toLowerCase()
  555. + System.getProperty("user.language");
  556. try {
  557. accounts = loadAccounts();
  558. } catch (NamingException e) {
  559. e.printStackTrace();
  560. }
  561. }
  562. }
Add Comment
Please, Sign In to add comment