Java字符串不可变如何提高安全性? [英] How does Java strings being immutable increase security?

查看:46
本文介绍了Java字符串不可变如何提高安全性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解到 String 是不可变的.当我阅读其背后的原因时,出现了一些原因,例如性能提高,或者由于无法修改其值,因此可以由多个线程共享.这些我确实理解的原因.

I just learned that a String is immutable. When I was reading the reason behind it a few reasons came up, for example performance increases, or since its value cannot be modified it can be shared by multiple threads. These reasons I do understand.

但是我不知道它与安全性之间的关系. String 是不可变的,对Java安全性有何帮助?

But I don't get how it is related to security. How does a String being immutable help in Java security?

推荐答案

编写类库的一种非常普遍的做法是将传递到API的参数存储在构造函数中,例如:

A very common practice in writing class libraries is storing the parameters passed into your API, say, in a constructor, like this:

public class MyApi {
    final String myUrl;
    public MyApi(String urlString) {
        // Verify that urlString points to an approved server
        if (!checkApprovedUrl(urlString)) throw new IllegalArgumentException();
        myUrl = urlString;
    }
}

String 可变的,这将导致微妙的利用:攻击者将传递一个好的URL,等待几微秒,然后将URL设置为指向攻击站点.

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.

由于不复制而存储是一种相当普遍的做法,并且由于字符串是最常用的数据类型之一,因此使字符串可变仍然会打开许多​​尚未编写但仍存在严重安全问题的API.使字符串不可变会关闭所有API(包括尚未编写的API)的特定安全漏洞.

Since storing without copying is a reasonably common practice, and because strings are among the most commonly used data types, leaving strings mutable would open up many APIs that are not written yet open to a serious security problem. Making strings immutable closes this particular security hole for all APIs, including the ones that are not written yet.

这篇关于Java字符串不可变如何提高安全性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆