0

Im trying to understand how String immutability increases the security. I had searched and found many cases but it does not give real practical example.

Here is one such example -

boolean connect(string s){
    if (!isSecure(s)) { 
        throw new SecurityException(); 
    }
    //here will cause problem, if s is changed before this by using other references.    
    causeProblem(s);
}

In the above case the connect method could be called with any valid String

For ex:- connect("DB2") or connect("ORACLE") and the method will be executed accordingly.

Can someone elaborate more on this how the security is enhanced?

Excuse if its more basic question.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 2
    What gave you the impression that `String` immutability increases security? – Elliott Frisch Nov 25 '14 at 02:45
  • Here is one such blog :- http://java.dzone.com/articles/why-string-immutable-java – user1050619 Nov 25 '14 at 02:48
  • Here is one more in SO- http://stackoverflow.com/questions/15274874/how-does-java-string-being-immutable-increase-security – user1050619 Nov 25 '14 at 02:50
  • That is *performance*; not *security*. – Elliott Frisch Nov 25 '14 at 02:51
  • This question should not be marked as duplicate..I read the SO question but could not understand "Were String mutable, this would lead to a subtle exploit: an attacker would pass a good URL, wait for a few microseconds, and then set the URL to point to an attack site." – user1050619 Nov 25 '14 at 02:55
  • This question is totally a duplicate, and I think entirely based on a flawed premise. `StringBuilder` is a mutable character structure. So Java does have them. The reason `String` is immutable is performance related. – Elliott Frisch Nov 25 '14 at 03:00
  • and its not security related, Correct? – user1050619 Nov 25 '14 at 03:21
  • Read the answer below. If there are security benefits, they're tangential. Again, `StringBuffer` and `StringBuilder`. Not to mention there are hacks with reflection to modify `String`(s). – Elliott Frisch Nov 25 '14 at 03:22

1 Answers1

0

There are also caveats in the opposite direction, for example some API avoid using String for passwords and prefer char[] (which can be erased in memory immediately after use, whereas a String may stick around for quite a while).

Thilo
  • 257,207
  • 101
  • 511
  • 656