Java字符串如何变为不可变增加安全性? [英] How does Java string being immutable increase security?

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

问题描述

我是Java新手,在学习时,我发现 String 是不可变的。当我阅读其背后的原因时,出现了一些原因,例如性能提升,因为它的值无法修改,并且可以由多个线程共享。这些原因我明白了。

但我不知道它与安全性有什么关系。 String 如何在Java安全性中成为不可变的帮助?

I am new to Java and when learning, I came across the fact that a String is immutable. When I was reading the reason behind it, a few reasons came up, for example performance increasements, since its value cannot be modified, and it can be shared by multiple threads. These reasons I do understand.
But I don't get how it is related to security. How does a String being immutable help in Java security?

请帮助我理解。在此先感谢。

Please help me in understanding. Thanks in advance.

推荐答案

编写类库的一种常见做法是存储传递到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;
    }
}

字符串 mutable,这会导致一个微妙的漏洞:攻击者会传递一个好的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天全站免登陆