Advertisement
Guest User

Untitled

a guest
Jul 19th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. class Password {
  2. public static void main (String args[]) throws IOException {
  3. Console c = System.console();
  4. if (c == null) {
  5. System.err.println("No console.");
  6. System.exit(1);
  7. }
  8.  
  9. String username = c.readLine("Enter your user name: ");
  10. /*
  11. This noncompliant code example reads user name and password information from the console and stores the password as a String object.
  12. The credentials remain exposed until the garbage collector reclaims the memory associated with this String.
  13. */
  14. String password = c.readLine("Enter your password: ");
  15.  
  16. if (!verify(username, password)) {
  17. throw new SecurityException("Invalid Credentials");
  18. }
  19.  
  20. // ...
  21. }
  22.  
  23. // Dummy verify method, always returns true
  24. private static final boolean verify(String username,
  25. String password) {
  26. return true;
  27. }
  28. }
  29.  
  30.  
  31.  
  32. //Compliant Solution
  33. class Password {
  34. public static void main (String args[]) throws IOException {
  35. Console c = System.console();
  36.  
  37. if (c == null) {
  38. System.err.println("No console.");
  39. System.exit(1);
  40. }
  41.  
  42. String username = c.readLine("Enter your user name: ");
  43. /*
  44. Console.readPassword() method allows the password to be returned as a sequence of characters rather than as a String object.
  45. */
  46. char[] password = c.readPassword("Enter your password: ");
  47. if (!verify(username, password)) {
  48. throw new SecurityException("Invalid Credentials");
  49. }
  50.  
  51. // Clear the password
  52. Arrays.fill(password, ' ');
  53. }
  54.  
  55. // Dummy verify method, always returns true
  56. private static final boolean verify(String username,
  57. char[] password) {
  58. return true;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement